I always tell my teams that neatness counts. Consider having to read a novel that is handwritten. The messier the handwriting, the harder it will be to read. That, in turn, can affect the time it takes to read the novel, enjoyment of the novel, and even understanding of what the novel is about! Thank goodness we don’t have to read handwritten books.
The same can be said for code. Messy (poorly formatted code) can increase the difficulty of understanding the intent and/or modifying the code.
Look at the code I recently came across. The code has been changed to protect the innocent and not-so-innocent. I had to make the font size really tiny to get everything on one line like it was originally. But, the spirit remains intact.
String string = (CyberProvince.findByCountryId((CountryParameters.findCountry()).getCountryId())).getProvinceNumber().toString()
So, image we have some objects that represent part of a hierarchy. In this case, we have provinces which are part of a country. And, to make things more interesting, we have the notion of a virtual province (CyberProvince). Anyway, from the code above it is a really difficult to see what is going on and who the actors are.
So, let’s make this readable. First, the parenthesis:
String string = (CyberProvince.findByCountryId( ( CountryParameters.findCountry() ).getCountryId() )).getProvinceNumber().toString()
In the very least, if you are using a buttload of parenthesis, then use some space to expose the “pieces”. Next, let’s extract a variable:
CountryParameters countryParameters = CountryParameters.findCountry();
String string = (CyberProvince.findByCountryId( ( countryParameters ).getCountryId() )).getProvinceNumber().toString()
A little better. Now, lets clean up some of the parenthesis, and extract a variable.
CountryParameters countryParameters = CountryParameters.findCountry();
Integer countryId = countryParameters.getCountryId()
String string = (CyberProvince.findByCountryId( countryId )).getProvinceNumber().toString()
Let’s extract another variable.
CountryParameters countryParameters = CountryParameters.findCountry();
Integer countryId = countryParameters.getCountryId();
CyberProvince cyberProvince = CyberProvince.findByCountryId( countryId );
String string = (cyberProvince).getProvinceNumber().toString()
Ok. Let’s do another round of parenthesis fixing.
CountryParameters countryParameters = CountryParameters.findCountry();
Integer countryId = countryParameters.getCountryId();
CyberProvince cyberProvince = CyberProvince.findByCountryId( countryId );
String string = cyberProvince.getProvinceNumber().toString()
Before the changes, understanding the code and considering modifications was much more difficult. Now, we can actually understand the intent. We can begin to analyze the code, to weigh the pros and cons of further refactoring of said code. Plus, we have the added benefit of being able to more easily debug the code if needed.
Once again: neatness counts!