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
- Place the method on the class where the result could be an attribute.
- Instance rather than class methods.
- Preferable none, or as few as possible, parameters.
Examples
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
-
- 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
|