Bustikiller
Bustikiller

Reputation: 2508

Refactor: Removing flags

I have a Java class such as:

public class className{
    public static void methodName(Object atr1, Object atr2, Object atr3, boolean flag){
        //Code here ...

        if(flag){
            executeASingleInstruction();
        }

        //Code here ...
    }
}

I know using flag parameters is a bad smell, and I would like to know If I could refactor this method in order to remove the flag parameter, or if it is better to keep this method the way it is right now.

Upvotes: 1

Views: 1418

Answers (3)

Erik Madsen
Erik Madsen

Reputation: 2014

Please note that there are more things to consider refactoring in your code, but here I will focus only on the boolean parameter smell.

You can refactor it by splitting up the method and deciding which one of the new methods to use at the place of invocation.

This will make your intention more clear at the point where you invoke either of the methods, especially if they have nice, descriptive names.

If I recall correctly, there is a section about it in Robert C. Martin's book: Clean Code: A Handbook of Agile Software Craftsmanship

public class className{
    public static void methodName1(Object atr1, Object atr2, Object atr3){
        encapsulation1(atr1, atr2, atr3);
        executeASingleInstruction();
        encapsulation2(atr1, atr2, atr3);
    }


    public static void methodName2(Object atr1, Object atr2, Object atr3){
        encapsulation1(atr1, atr2, atr3);
        // no execution of aforementioned instruction
        encapsulation2(atr1, atr2, atr3);
    }
}

Upvotes: 3

JBALI
JBALI

Reputation: 89

Try to make it staticenter code here

public class className{
        public static void methodName(Object atr1, Object atr2, Object atr3, boolean flag){
            //Code here ...

            if(flag){
                executeASingleInstruction();
            }

            //Code here ...
        }

        private static void executeASingleInstruction() {
            // TODO Auto-generated method stub

        }
    }

Upvotes: 0

Roman C
Roman C

Reputation: 1

Don't use static method, and you can use object properties if you need to set the flag, also you can provide the flag in the constructor.

public class ClassName{

private boolean flag;
//getter setter

public ClassName(){}

public ClassName(final boolean flag){this.flag = flag;}

public void methodName(Object atr1, Object atr2, Object atr3){
    //Code here ...

    if(flag){
        executeASingleInstruction();
    }

    //Code here ...
}
}

Upvotes: 0

Related Questions