Obeying best practices blindly is not a best practice.
Tackling the Arrow head Anti-Pattern
Frequently you will see following type of code in your code base.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| if(result != 1){ if(someOtherResult == 101) { if(anotherValue == 500) { // do something } } else { // do some other thing }}return; |
Here the code forms a shape of an arrow-head, as below:
1
2
3
4
5
6
7
8
9
| if if if if do something end end endend |
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| if(result == 1){ return;}if(someOtherResult == 101 && anotherValue == 500){ // do something return;}// do some other thingreturn; |
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| if(IsValidResult(someOtherResult, anotherResult){ // do something return;}bool IsValidResult(int someOtherResult, int anotherResult){ if(someOtherResult == 101 && anotherValue == 500) { return true; } return false;} |
Subscribe to:
Comments (Atom)