Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A design pattern to avoid multiple ifs

I have a really awfull class with two methods that start or stops some services when that services are available. Something like the following (they are not if-elses, just if):

void startServices() { 
if (service1 == true) { 
  start1();
}
if (service2 == true) { 
  start2();
} if (serviceN == true) { 
  startN();
} 
} 


void stopServices() { 
if (service1 == true) { 
  stop1();
}
if (service2 == true) { 
  stop2();
}
if (serviceN == true) { 
  stopN();
}

}

Do you recommend me any design patter to make it prettier?

Thanks!

like image 835
biquillo Avatar asked Oct 21 '11 02:10

biquillo


2 Answers

Depends; my first reaction is to store the services in a hash or array. Each service implements an interface with start and stop methods. Starting or stopping a service then requires only a service key or index.

It's still a bit brittle, perhaps, but without known more I'm not sure how to "domainify" ut so it looks more like what you're doing.

like image 134
Dave Newton Avatar answered Oct 13 '22 03:10

Dave Newton


You can use the Strategy pattern.

The idea is that you should know what strategy you're going to use when you instantiate your class (or you can change it dynamically latrr). Therefore, you can pass in that strategy upon instantiation (and optionally replace it later).

public interface IStartupStrategy
{
    void Start();
}

public interface IStopStrategy
{
    void Stop();
}

public class MyClass
{
    private readonly IEnumerable<IStartupStrategy> startupStrategies;
    private readonly IEnumerable<IStopStrategy> stopStrategies;

    public MyClass(IEnumerable<IStartupStrategy> startup, IEnumerable<IStopStrategy> stop)
    {
        this.startupStrategies = startup;
        this.stopStrategies = stop;
    }

    public void Start()
    {
        foreach(var strategy in this.startupStrategies)
        {
            strategy.Start();
        }
    }

    public void Stop()
    {
        foreach(var strategy in this.stopStrategies)
        {
            strategy.Stop();
        }
    }
}
like image 35
cwharris Avatar answered Oct 13 '22 03:10

cwharris