2

I'm trying to implement a feature with option to turn it on/off based on a flag. I'm doing it in the following way which I feel like a overkill,

public interface Feature {

    public interface EnableState {
        void execute();
    }
    public interface DisableState {
        void execute();
    }
}

Exposed an interface so that each and every feature in my project could make use of it to define their own way of enabling or disabling a feature.

public class PlaySound implements Feature.DisableState, Feature.EnableState {

    //Feature is turned off by default
    boolean status = false;
    private static final PlaySound playSound = new PlaySound();

    public static PlaySound getInstance() {
        return playSound;
    }

    private PlaySound() {
        //Compute and update the feature status
    }


    Feature.DisableState disabledState = new Feature.DisableState() {

        @Override
        public void execute() {

        }
    };

    Feature.EnableState enabledState = new Feature.EnableState() {

        @Override
        public void execute() {

        }
    };

    @Override
    public void execute() {
        if(status) enabledState.execute();
        else disabledState.execute();
    }
}

Which I feel like a overkill. Does the code smell bad?

Instead should I have implemented in this way,


if(featureEnabled) {
   //do something
} else {
   //do nothing
}

1

1 Answer 1

4

If you have just one of such features, you'll have the choice, and the simplest, the better.

However, the problem with long-living feature flags, is that they tend to multiply with the evolution of the features. With conditionals, it might then become very error prone, for example:

if (featureAEnabled || feabtureBEnabled) {
    ...
    if (featureBEnable && !featureCEnabled) {
        ...
    } else 
        ...
}
... 

This is why it may make sense to design it more carefully:

  • One way of doing it is the strategy pattern, by injecting a strategy in the object that offers the behavior.
  • Another way the state pattern that seems to be used in your case.

Of course, for simple cases it may be overkill. But the advantage is that you avoid the combinatorial effect of multiple (sometimes interdependent) flags in conditionals.

Finally, some people have spent a lot of time investigating this issue and came out with the concept of feature toggle. Their advice is also to avoid conditionals, and invert the control by injecting the feature rather than querying the flag.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.