Continuing with the ‘Java good practices’ series, Timothy Fagan at NYC Java meet up, brought us an interesting discussion about code complexity. For many people it could sound as a ‘Capitan obvious’ advise, although all of us at some point made one of these mistakes bad decisions, when writing software. So, this is what I learn from the talk, including some personal points of view.
Be simple.
Minimalism is just beautiful, why don’t apply it to code? The most comprehensible and short a method is, the more easy to debug and maintain it will be; people would prefer to work with defective and understandable code than working with perfect and incomprehensible code. In the first case you can fix the code without any problem, in the second case, if you want to modify the code, you will need to spend some extra time deciphering how it is supposed to work. I like to think methods are la Haikus, short in length and powerful in meaning. (Ok some haikus are really difficult to interpret what would make this a bad analogy, but let’s stick to the easy ones)
Reduce possible execution paths
Cyclomatic complexity is defined by wikipedia as “the count of the number of linearly independent paths through the source code”, what means, the more decision points you code have, the more complex it is to read, test and finally execute; the advice here is, if you have a lot of conditions in a single method, probably you would be likely to refactor your code, grouping conditions, moving responsibilities to another method/class or removing unnecessary validations.
For example System.getProperties() !=null , consider that the JVM will never return you a null object, so this checking its unnecessary.
Also try to reduce the number of return statements in your methods, some authors recommend to have just one return at the end of the method, but sometimes you can make your code faster if write an early return for the most common execution scenarios.
Be positive.
Seems like human brains are shaped to assert to ‘true’ statements, therefore you should code your Boolean conditions asking if the value is true, it would be easy to read for the fellow maintenance developer.












{ 2 comments… read them below or add one }
Nice advices… yes, they seems pretty obvious, but, how many times we find ourselves writing code that smells bad?
Someone told me, that if you looks your 1 year old code, surely it stinks. It’s never ending process of design and refactoring…