Deeply Nested Code

Encountered a deeply nested code (see below) or arrow code. Based on past experiences, you know this is sure going to turn into a maintenance hell as readability is low and modifiability is next to impossible.

Sample simplified pseudocode.
if ( condition a ) {
    if ( condition b ) {
        if ( condition c ) {
            foreach ( ...) {
            }
        }
    }
}

How we going to solve this ? Flatten the nested code. How ? From the  Refactoring book by Martin Fowler, you can either use Extract Method or Replace Nexted Condition with Guard Clauses.

Sample refactored pseudocode.
if ( ! condition a ) return something_not_a;
if ( ! condition b ) return something_not_b;
if ( ! condition c ) return something_not_c;
do_something_with_foreach_loop();

No comments:

Post a Comment