24 January 2007

Everything is a class

A good general rule of OO is to look at everything as a class. If you design with classes in mind, you get all of the benefits of polymorphism-encapsulation-inheritance and all of that other crap you need to spew out in interviews. This approach of class-centric design should be remembered even when using raw data types--a point that is easy to forget.

I recently ignored this rule on some simple code I was working on at home. The code manipulated an array of days ("Monday," "Tuesday," etc.). Halfway through coding some bloated utility functions, I came to my senses and quickly refactored. The value of OO--encapsulation specifically--was immediately apparent. Sometimes you get sloppy and forget, and sometimes you file it under "To Be Fixed Later." Far too much corporate code gets written in that way. It's easier to add comments to your code as you're writing it than at a later time (which never comes). Similarly, it's easier to encapsulate data earlier.

This shoud be, and indeed does sound like, a very duh point, but it's one that gets ignored.

So anyway, the day array began as a simple string array. A collection class provides sort and search and management methods, so I didn't design any further than the collection class. Almost immediately, utility methods started appearing: convert from a delimited list, convert to a delimited list, check for a weekday, check for a weekend. All of these were small but invasive to the surrounding code. In a situation where a simple true or false result was needed, access to the collection required a search and comparison that included one or more temporary objects. If only one spurious type is involved, then your code would not get too mangled. However, many similar nearly-basic types are used throughout programs, and those incur an unwieldy increase in local noise in the form of utility code. As local objects and line lengths increase, readability decreases. It's never one or two extra lines that you're adding, it's the potential for 10s or 100s.

I caught my lazy error early, and the simplification to the code was ... breathtaking. An added bonus--as always with encapsulation--was that the newly created class provided a chance to add additional safety checks that would be avoided the in already-complex surrounding code. Again, this seems like a simple Programming for Dummies recommendation because it's so obvious, and yet it is too often avoided with no good excuse. LOC numbers may go down, but so do headaches.

[ posted by sstrader on 24 January 2007 at 2:21:09 PM in Programming ]