Message Sends are Plans for Reuse
Damien Cassou, Stéphane Ducasse and Luc Fabresse
http://stephane.ducasse.free.fr
About This Lecture
Another design lecture:
- Next step of the
not
implementation lecture
- Relevant to any object-oriented language
- May change your view on design
What You Will Learn
- Message sends are hooks for subclasses
- "I like big methods because I can see all the code" leads to bad design
- Why writing small methods is a sign of good design
Sending A Message Leads to a Choice
- a message send leads to a choice
- a class hierarchy defines the choices
self
always represents the receiver
- method lookup starts in the class of the receiver
An Example
We want to change the defaultNodeSize
formula in a subclass
Duplication
Duplicate the code in a subclass
Avoid Duplication
- in Java-like languages, using
private
attributes makes duplication in subclasses impossible
- duplication is not a good practice:
- duplication copies bugs
- changing one copy requires changing others
Solution
- send messages
- define small methods
Subclasses can override such methods
We can Refactor this
Better Design
Subclasses Reuse Superclass Logic
A subclass can refine the behavior
Another Step
We can also extract the UINode
instantiation.
Another Step
Do Not Hardcode Class Use
Define Methods Returning Classes
Many Small Messages
- Some developers complain about all these small methods
- They try to understand code line by line
- This does not scale
Small messages are a sign of good design
Avoid Magic Numbers
- subclasses may want to change values
- do not hardcode magic numbers (55)
Use a Message Send
- this gives a name to a value
- subclasses can override the value
How to let the class users change the value?
Use an Instance Variable
- subclasses can override the value
- class users can set the value
Gruyere-Oriented Programming
Conclusion
- Code can be reused and refined in subclasses
- Sending a message in a class defines a hook:
- i.e., a place where subclasses can inject variations
- Prefer small methods because:
- this gives names to expressions
- this gives freedom to subclasses
/