Methods – Part 3

Part 3 – Unit 2: Methods (Computer Science 30S)

If you don’t feel like reading this web page, here are two alternatives:

  • Read this presentation of the same content (slides 46 – 57)
  • Watch this playlist of videos of the same content on YouTube

Content Sections:

  1. Overloading a Method
  2. Method Methodology

Overloading a Method

  • In OOP, you can overload methods
  • Overloading means that you create more than one method with the same name
  • Each method can have the same name, but a different distinct parameter list, that Java can use to determine which form of the method you wish to use
  • For example:

Capture(2dd3)


Method Methodology

  • The same programming techniques that are used to construct good programs should be used to construct good methods
  • That is:
  • (1.) Analysis: In the first step, determine what the method is supposed to accomplish,
  • This is ‘understanding the problem
  • (2.) Design
  • Next, according to the analysis, the design determines what information needed from the caller, and what should be returned:

Capture2(ddd16)

  • Design your method with this in mind…
  1. It should perform a singlewell defined task
  2. It’s name and parameter names should be descriptive of what it does so that it is understandable to programmers reading the method
  3. It should be short; a long method implies that the code should be further decomposed (perhaps using top-down)
  • (3.) Coding
  • When coding in your method remember to document throughout and perhaps add a delimiter to separate various methods
  • For example…

Capture3(1ff0)

  • When you add simple code to just indicate the method exists this is known as a ‘stub
  • (4.) Testing and Debugging
  • The best method for this is to write just enough code to test each method (this is often called a ‘driver’ method) during development
  • You can easily cause errors by writing an entire program and its various methods then testing them all
  • More bugs will pop up, and they will be harder to detect
  • (5.) Documentation and Maintenance
  • Remember to properly document method using proper technique (like JavaDoc) or the traditional purposepreconditions, post conditions, and calls to any other Methods

The NEXT thing to work on is the “Methods Example 3” example page