Design pattern to avoid multiple ifs

I have a really cool class with two methods that start or stop some services when these 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(); } } 

Have you recommended me any project to make it more beautiful?

Thanks!

+6
source share
4 answers

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

This is perhaps a little fragile, but without knowing more, I'm not sure how to β€œcomplement” it, so it looks more like what you are doing.

+4
source

You can use the strategy template.

The idea is that you should know what strategy you are going to use when creating an instance of your class (or you can change it dynamically). Therefore, you can pass on this strategy after creating the instance (and possibly 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(); } } } 
+4
source

Use objects in which you have a list of services that you can iterate through by disabling them using the inherited stop () method.

 public interface Service { void start(); void stop(); } public class TestService implements Service { @Override void start() { } @Override void stop() { } } 

Each service can also maintain its state in order to disable them only if they are turned on.

+2
source

Switch statements are less confusing. If used together with an enumeration code, it becomes very readable.

0
source

Source: https://habr.com/ru/post/899750/


All Articles