I happened to notice the book “The ThoughtWorks Anthology” lying around the office. It contains quite a few interesting articles. One in particular resonated with me.
In Chapter 6, Jeff Bay talks about a set of simple rules for writing OO code, which he suggests you try applying rigorously on a small project (say 1000 lines of code). The article can be downloaded here.
This is a hard exercise, especially because many of these rules are not universally applicable. The fact is, sometimes classes are a little more than 50 lines. But there’s great value in thinking about what would have to happen to move those responsibilities into real, first-class-objects of their own. It’s developing this type of thinking that’s the real value of the exercise. So stretch the limits of what you imagine is possible, and see whether you start thinking about your code in a new way.
What I liked about this article is that it cut to the core of something which I have been working at explaining over the last few months. I sometimes feel like a “purist” when discussing OO design. It is a common situation to find myself defending writing a small class, or encapsulating a String to make a small value object which only has a single attribute. Jeff explains in a great way a few principles and challenges the reader to try them out in a rigorous way, just to see how it works out. This is a great way to present it, its not saying “I know the right way and you must follow the rules”, its suggesting that you should give it a chance and you might begin to see some rewards, or “Try it, you might like it”.
I also liked the fact that eight out of the ten rules were all about encapsulation something I have also been thinking a good deal about recently, prompted by this experience, even to the extent of getting it printed on a t-shirt (but that’s another story).
Since writing this post, I have had a discussion with Jeff via email, the results of which can be found here, this paragraph is superseded.
Another one which isnt actually in the book, but that I have been getting into recently is “No static methods except as factories”, This one is particularly hard to follow when so many libraries use them and its just so convenient:)
He’s not suggesting that these rules are always applicable but I think its interesting to make the effort of taking it to an extreme and see where it leads you, it may open new possibilities when going back to everyday coding.