I really enjoyed Jeff’s post on Spartan Programming. I agree that code like that is a joy to read. Unfortunately, I’m not so sure it would necessarily be a joy to work with.
For years I have read about and adhered to the ‘one-expression-per-line’ practice. I have fought the good fight and held my ground when many programming books countered this advice with example code like:
while (bytes = read(...)) { ... } while (GetMessage(...)) { ... }
Recently, I’ve advocated one expression per line for more practical reasons – debugging and production support. Getting a log file from production that claims a NullPointer exception at ‘line 65’ which reads:
ObjectA a = getTheUser(session.getState().getAccount().getAccountNumber());
is frustrating and entirely avoidable. Short of grabbing an expert with the code that can choose the ‘most likely’ object that was null … this is a real practical pain.
One expression per line also helps out quite a bit while stepping through code. I practice this with the assumption that most modern compilers can optimize away all the superfluous temp objects I’ve just created …
I try to be neat – but cluttering my code with explicit objects sure feels laborious at times. It does not generally make the code easier to browse – but it really has come in handy when tracing things down in production or stepping through my or someone else’s code.
What style do you advocate and can you rationalize it in a practical sense?
In The Pragmatic Programmer Hunt and Thomas talk about a study they term the Law of Demeter and it focuses on the coupling of functions to modules other than there own. By allowing a function to never reach a 3rd level in it’s coupling you significantly reduce the number of errors and increase the maintainability of the code.
So:
Is close to a felony because we are 4 objects down the rat hole. That means to change something in one of those objects I have to know that you called this whole stack right here in this very method. What a pain.
Better:
Note this runs counter to the expressive forms of programming that are now really popular with mocking software. The trade off there is that you have a tightly coupled interface anyway, and the expressive syntax just makes it easier to use.