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.
- Techniques after using Swift for a month posted by sstrader on 26 August 2015 at 11:41:51 PM
- Some thoughts on Ruby after finishing a week (minus one day) of training posted by sstrader on 15 December 2011 at 8:59:30 PM
- Links on the singleton pattern posted by sstrader on 9 December 2011 at 9:19:50 AM
- Phonebot posted by sstrader on 29 October 2011 at 6:37:05 PM
- The labeled break in Java posted by sstrader on 4 September 2011 at 11:27:56 AM