Java-8 – Java prevents a lot of if and replaces it with design patterns
I use this code in my application and I find it very ugly
for (final ApplicationCategories applicationCategorie : applicationCategories) { if (applicationCategorie == ApplicationCategories.PROJECTS) { // invoke right method } else if (applicationCategorie == ApplicationCategories.CALENDAR) { // ... } else if (applicationCategorie == ApplicationCategories.COMMUNICATION) { } else if (applicationCategorie == ApplicationCategories.CONTACTS) { } else if (applicationCategorie == ApplicationCategories.DOCUMENTS) { } else if (applicationCategorie == ApplicationCategories.WORKINGBOOK) { } }
My goal is to handle the enumeration of all application categories contained in the enumeration list
Solution
The least you can do is declare methods that handle behaviors that depend on enumerations in applicationcategories Thus, if you want to add a new value to the enumeration, you only need to change the code relative to the enumeration
In this way, your code follows the principle of open and closed, so it is easier to maintain
enum ApplicationCategories { PROJECTS,CALENDAR,// And so on... WORKINGBOOK; public static void handle(ApplicationCategories category) { switch (category) { case PROJECTS: // Code to handle projects break; case CALENDAR: // Code to handle calendar break; // And so on } } }
This solution works only if you do not need any external information to process enumeration values
Remember, you can also add fields to enumeration values
edit
If necessary, you can also implement the policy design pattern First, define the policy interface and some concrete implementations
interface CategoryStrategy { void handle(/* Some useful input*/); } class ProjectStrategy implements Strategy { public void handle(/* Some useful input*/) { // Do something related to projects... } } class CalendarStrategy implements Strategy { public void handle(/* Some useful input*/) { // Do something related to calendars... } } //...
You can then modify the enumeration to use the above policy
enum ApplicationCategories { PROJECTS(new ProjectStrategy()),CALENDAR(new CalendarStrategy()),// And so on... WORKINGBOOK(new WorkingBookStrategy()); private CategoryStrategy strategy; ApplicationCategories(CategoryStrategy strategy) { this.strategy = strategy; } public static void handle(ApplicationCategories category) { category.strategy.handle(/* Some inputs */); } }
Obviously, the above code is just a sketch