Obeying best practices blindly is not a best practice.
Tuesday, September 30, 2014
Thursday, September 18, 2014
Frequently you will see following type of code in your code base.
Here the code forms a shape of an arrow-head, as below:
If you see, the main logic is deep down into the nested condition, it increases the cyclomatic complexity of the code.
A better version of the same code could be as below:
The above code does a number of things to flatten the code and make it better:
- Validations are performed first and it returns at the first opportunity.
- Multiple nested conditions are combine into one (with “&&”(logical And) operator. If there are multiple expressions forming one such condition, they can be moved to a separate method returning boolean. That method can then be use in the if condition as below: