避免使用布尔标志作为属性

Ste*_*ett 3 refactoring design-patterns boolean

首先,我想说我在重构方面没有太多经验,也不知道这是否是偏离主题的.

我正在使用给定代码,其中使用了许多布尔属性,由于可读性,我想避免使用它,并且我不知道如何以正确的方式处理它.

class MyClass(){
    boolean a;
    ...
    void function(){
        ...
        a = true;
        ...
    }

    void anotherFunction(){
        ...
        if(a == true){
            //do something
        } else {
            //do something else
        }
        ...
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

boolean a在多个使用function人就像这样,在anotherFunctions的运行有关的代码a.由于使用了多个属性和局部变量,因此很难理解代码和依赖关系,而且我很难重构它anotherFunction.重构这一点的努力可能非常高.

我一直试图避免使用像这样的布尔值,因为在我看来这不是一个好习惯.如果我错了,请不要犹豫,纠正我.

现在我想知道我是否应该重构代码并花费精力?在这种情况下是否可以使用某种模式?

JB *_*zet 6

您可以使用状态模式.根据单独抽象State类中的布尔变量封装状态和行为.当boolean设置为false时,将状态更改为FalseState(扩展State)的实例,并委托给此FalseState实例.当boolean设置为true时,将状态更改为实例TrueState,并委托给此TrueState实例.

例如,以下类

public class Apple {

    private boolean fresh = false;

    public String getColor() {
        if (fresh) {
            return "green";
        }
        else {
            return "brown";
        }
    }

    public void setFresh(boolean fresh) {
        this.fresh = fresh;
    }
}
Run Code Online (Sandbox Code Playgroud)

可以重构为

public class Apple {

    private AppleState state = new OldAppleState();

    public String getColor() {
        return state.getColor();
    }

    public void setFresh(boolean fresh) {
        this.state = state.nextState(fresh);
    }

    private static abstract class State {
        public abstract State nextState(boolean fresh);
        public abstract String getColor();
    }

    private static class OldAppleState extends State{
        public State nextState(boolean fresh) {
            return fresh ? new FreshAppleState() : this;
        }
        public String getColor() {
            return "brown";
        }
    }


    private static class FreshAppleState extends State{
        public State nextState(boolean fresh) {
            return fresh ? this : new OldAppleState();
        }
        public String getColor() {
            return "green";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用内部类,但你当然可以使用顶级类.