Coding Secret …
Saturday, July 31st, 2010I’m sitting at a cafe at 8am sipping a nice coffee while I write this. You may not find this very exciting but for me is it quite out of the ordinary as I usually spend this time with my wife and twin sons. Would you find it exciting if I was to tell you that I would reveal a single little thing you can do to your code that will improve it for you and for everyone else that uses it?
With the one piece of advice I’m going to tell you how to reduce the amount of code you write so you can keep your code dry’er , do things quicker because you are doing less, and make your code more readable and a better match for your domain. Does this sound too good to be true?
The advice is to never use a primitive collection as a domain object. To be clear this advice also means that a primitive collection cannot be exposed outside of the containing Class.
What I usually see in code is the use of a primitive collection to represent a domain model concept or in place of a proper class. I guess this is usually done because it is thought to save time or that this is what these types are for. The code looks like this (in Java for the masses):
List<Account> accounts;
for (Account account : accounts) { do something with account }
The key point of the advice is the use of “List<Account>” should only appear in the definition of a Class called Accounts. Try this advice and see positive benefits for yourself.
After this advice is applied the Accounts class then represents a concrete concept in the domain which was missing before, although it was implied. Accounts can now have methods that represent domain concepts and they will exist in a single place, not scattered or duplicated throughout the code. Want to know what business happens with a collection of Accounts, just look at Accounts.
The advice applies to more than just primitive collections but I thought I would start there as they represent a common usage. The advice can also be applied to less obvious collection types like File. For example, don’t just use a File object but subclass it and name the class to represent what is in the file, giving more meaning to “File” and the things that you want to do with that file.
This advice is not just for Java programmers, although most of the code examples around promote this primitive approach. Many non-Java languages like Ruby have great support for collections but these too should not be used in place of a concrete class.
When I apply this advice to my own code (in Ruby, Smalltalk and Java) the result is more meaning in the model and less code. Please give it a try and let me know your experiences.