Switch Design for Boolean Combinations

Suppose I have n Boolean values, where n is a relatively small number (3-5 or so). Let's say that values ​​are class properties, each of which can be set or disabled independently. Thus, 2 combinations of n are possible. Now I want to distinguish between these combinations in a switching manner. Currently, I usually do something like this:

int mask = (bool1 ? 1 : 0) + (bool2 ? 2 : 0) + (bool3 ? 4 : 0) + ... ; switch (mask) { case 0b000: // all variables false case 0b001: // only bool1 true case 0b011: // only bool1 and bool2 true ... } 

It works well, but I don't find it very elegant. Is there some good practice (in Java) or a Java idiom for such cases?

+5
source share
1 answer

This problem is the reason that they came up with a sample Design Decorator . The template allows you to add "features" to your class. For example, let's say you have a Coffee class. Each instance of coffee can be with sugar, milk, cream, sweeteners, or whipped cream (let none of them be mutually exclusive). Therefore, instead of five logical parameters (one for each coffee characteristic). You will have the following hierarchy:

 public interface Coffee { public void drink(); } public class CupOfCofee implements Coffee { public void drink() { print("Yumm coffee"); } } abstract class CoffeeDecorator implements Coffee { protected Coffee decoratedCoffee; public CoffeeDecorator(Coffee decoratedCoffee) { this.decoratedCoffee = decoratedCoffee; } public void drink() { decoratedCoffee.drink(); } } // We will provide coffee with sugar as an example. public class CoffeeWithSugarDecorator extends CoffeeDecorator { public CoffeeWithSugarDecorator(Coffee decoratedCoffee) { super(decoratedCoffee); } @Override public void drink() { print("Yumm sugar"); super.drink(); } } // Here is how you will initialize a coffee instance with sugar and milk. Coffee coffee = new CoffeeWithMilk(new CoffeeWithSugar(new CupOfCoffee())); 

This design makes your code more readable and extensible, dividing the behavior of each logical parameter into a separate class. The defiant drink will print: "Yumm sugar milk Yumm coffee milk"

0
source

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


All Articles