Methods

Monday, 20 May 2002
What is the best location for a method? Where does the responsibility belong?

Here are three rules of thumb to find the best place for methods in a class tree.

Rules of Thumb

  1. Place the method on the class where the result could be an attribute.
  2. Instance rather than class methods.
  3. Preferable none, or as few as possible, parameters.

Examples

OO model of cup, pen and pencil

What colour is a pencil?

Rule 1, attribute
The attribute colour should be in WritingUtensil, the abstract super class of Pen and Pencil.
Rule 2, instance rather than class
This method is an instance method of pencil and pen. So, the best place is the abstract class WritingUtensil.
Rule 3, no parameters
Parameters are not necessary.
Solution: Make a concrete instance method getColour() in the abstract class WritingUtensil.

What is the number of pencils in a cup?

Rule 1, attribute
The imaginary attribute "numberOfPencils" would reside in Cup.
Rule 2, instance rather than class
For Pencil this would be a method at class level. A better choice is an instance method in Cup.
Rule 3, no parameters
A class method in Pencil would need an instance of Cup as parameter. A better alternative is an instance method in Cup, without parameters.
Solution: Create an instance method getNumberOfPencils() in Cup.

Put Pen in Cup

Rule 1, attribute
  • The attribute for implementation of the one-to-many association Cup-WritingUtensil is possible in Cup. An instance of Pen would be an element of some collection within an instance of Cup.

    When a pen moves from one cup to another two collections must change:

  • A better possibility is one attribute "Cup" in WritingUtensil, as imaginary implementation of the many-to-one association. This one attribute with one possible value is a much better idea.

    In the real code a method in WritingUtensil called setCup(Cup) is not too bad either. This method does all the work:

    1. It updates the many-to-one association in WritingUtensil. Behind the scenes it calls protected method of Cup:
    2. remove(WritingUtensil) to remove the pen from the old cup.
    3. add(WritingUtensil) to add the pen to the new cup.
Rule 2, instance rather than class
This method is an instance method, either in Cup or WritingUtensil.
Rule 3, no parameters
Both implementations, in Cup and WritingUtensil need a parameter.
Solution: Put the responsibility for the association at the 'many' side. Create a public method putInto(Cup) in WritingUtensil.

What is the number of Cups?

Rule 1, attribute
The attribute "numberOfCups" would be an attribute of the class Cup.
Rule 2, instance rather than class
This method has to be a class method.
Rule 3, no parameters
There is no need for parameters.
Solution: Create a class method getNumberOfCups() in Cup.

Till next week,
Nut