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!
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.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With