Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

When the context class can accept a null strategy, is there another way to do it without check if its null?

Is this considered a good strategy design implementation?

class MainApp{
    static void Main(){
        Context context = new Context();
        while(true){
            Strategy strategy = createConcreteStrategy(Console.ReadLine());
            context.setStrategy(strategy);
            context.run();
        }
    }
    static void createConcreteStrategy(string input){
        if( input == "strategyA" ){
            return new StrategyA();
        }
        if( input == "strategyB" ){
            return new StrategyB();
        }       
        return null;
    }
}
abstract class Strategy { public abstract void doSomething(); }
class Context{
    Strategy strategy;
    ClassX x;

    public Context(){}
    public void setStrategy(Strategy strategy){
        this.strategy = strategy;
    }
    public void run(){
        if( strategy != null ){
            data = strategy.doSomething();
            x.setData(data);
        }
    }
}
share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

There is absolutely a way to avoid checking for null here! Use the null object pattern, i.e.

class NullStrategy: Strategy {
    public void doSomething() {
    }
}

and then the "default" case in createConcreteStrategy is return new NullStrategy() instead of return null, and then you no longer have to check if strategy is null in run.


If you don't want to call x.setData with a null argument, then you could pass x to the strategy. Here's one possible implementation:

class NullStrategy: Strategy {
    public void doSomething(ClassX x) {
        // don't do anything with x
    }
}

class RealStrategy: Strategy {
    public void doSomething(ClassX x) {
        var data = someOperation();
        x.setData(data);
    }
}

Pushing an if-statement into an instance of Strategy makes sense to me in this situation.

share|improve this answer
    
I was thinking about null object pattern as well, but ClassX has to check if data is null. Doesn't that defeat the purpose of null object pattern? –  user658091 May 18 '13 at 5:22
    
@user658091 I updated my answer to explain how to avoid that issue. –  Mark Rushakoff May 18 '13 at 5:29
    
+1 I feel the "null object pattern" is a misnomer. It should have been named the NOP Pattern. NOP standing for NO oPeration as in the NOP assembly instruction. –  Marjan Venema May 18 '13 at 11:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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