OO design is a creative activity. To be successful at it, you’ll need a mixture of both talent and learned skills. There is no such thing as correct design. There is only good, bad and somewhere-in-between design. OO program is simply a collection of objects that send messages to each other. But how do you design these objects? What objects to create? Which objects should interact? In my work, I usually begin OO design by identifying abstractions. I look at the problem from higher level. I try to identify abstractions that model true nature of the problem. An common mistake is to completely model real-world entities. In software development we have possibility of using abstractions to make our job/life easier. You should use this to your advantage. I assign each object a single responsibility. Note that assigning responsibilities is not easy at all. If you are good at assigning responsibilities then chances are, that you’re are good at OO designs too.
“Understanding responsibilities is key to good object-oriented design”—Martin Fowler
Once you’re done with the design, how do you know if it’s good or bad? There are two metrics/principles that you can evaluate your designs against. These are coupling and cohesion. These principles are very powerful in assisting you to make your OO designs good. Funnily, the principles don’t even come from OO, but from Structured design. Coupling is simply a degree to which each object is dependent on each one of the other objects (Wikipedia definition). Coupling quantifies the dependencies among objects. It can be loose or tight. Loose coupling is desired, since it’s more change-friendly. Fewer dependencies make introducing changes easier. Cohesion tells us how focused a class is in fulfilling its responsibility. Does a class have well defined responsibility? Are all parts of class (methods etc) focused on fulfilling that, and only that responsibility? High-cohesion is desired, since it promotes robustness, reusability, and understandability.
To sum up, here are the key concepts I use in my day-to-day OO design:
- Abstractions
- Responsibilities
- Loose-coupling
- High-cohesion
Following books helped me to gain more understanding of OO design:
- Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development by Craig Larman. This book is a great place to start. It will teach you UML as well, and how to use it effectively.
- Object Design: Roles, Responsibilities, and Collaborations by Rebecca Wirfs-Brock. I haven’t read it completely ,gets kind of boring at some parts, but there are some great insights on OO design.
- Object-Oriented Design Heuristics by Arthur J. Riel – a bit old, but great book.
Final advice: The best way to become better at OO design is to do it a lot. A huge amount of it.