In objects, we model the world around us via behavior and state. The operations performed by the object define it’s behavior, and the objects specify their behavior via methods and messages.
Objects can hide their representation behind messages:
class House def build install_floor raise_walls add_roof end end
Code is easier to read when we decompose functionality and use messages. In the example above, we can see that in order to build a house we install the floor, raise the walls, and add a roof. These methods handle the details of the implementation, and might even be broken down into more messages depending on the complexity of the task.
Decomposing the functionality of your program into smaller, digestible, and carefully named methods clearly communicates your intentions to the reader.
Centralizing the meat of the algorithm might make code easier to follow, since you don’t have to jump around from file to file to understand it, but this approach leads to rigid systems. If you break up behavior into many methods and pass messages around to carry out tasks, you increase flexibility by essentially making your objects replaceable. Managing many bits and pieces of code takes time and effort, sometimes bigger methods could be better if the management overhead outweighs the benefits of decentralizing the flow of control.
In Smalltalk Best Practice Patterns, we can find an extensive list of behavior patterns gathered by Kent Beck. He splits behavior patterns into methods and messages. Method patterns deal with the decomposition of a program into methods, and how to write those methods throughout your system, while Messages patterns deal with how to compose and decompose your messages, and how to pass those messages between the components of your system in order to achieve complex tasks.
It’s really interesting to put a name on strategies I’ve used in the past and see why they work. I found a few pretty cool patterns that I didn’t know about, but they’re exclusive to Smalltalk. I’ll write about my favorites on a separate blog post.