mardi 4 septembre 2018

Nested if-object-null-return method extraction or alternative for sonar cognitive complexity

In most cases when an object is optional, it is possible to use Guava to help in if null checks. But in cases where the statement is used to decide if the method is going to return earlier (from what I experienced) even that is not enough.

My question regards the use of nested if-statements to return a default value instead of continuing with the method execution.

Here's an example of what I mean:

private MyObject myMethod(Object object, Object object1, Object object2) {

    /* implementations... */
    if (object == null) {

        /* implementations... */
        if (object1 == null) {
            return new MyObject();
        }

        /* implementations... */    
        if (object2 == null) {
            return new MyObject();
        }

    } else {

        /*same structure shown in if-statement...*/

    }

    /* implementations... */

    return new MyObject(/* with args */);

}

I am looking for a solution that solves the problems of cognitive complexity indicated sonarQube in which the amount of 'if' and nested 'if' statements used in the method increments the complexity of the code.

In other words, ways to extract the statements from the method into another method or solving them through other ways that don't involve if-statements.

Aucun commentaire:

Enregistrer un commentaire