How to reorganize multiple complex if-else branches

This issue relates to software used by companies that organize events. When an action changes (status, start time, number of people), some people need to be notified of this (via email). The code responsible for this started very simply: the body of the email contained all the old values ​​and new values ​​of the information that was changed.

Over the years, many small rules have been introduced. For example: if the new status is "canceled", the subject of the letter should be: "Action canceled" instead of "Action changed." If there is no previous status (therefore, a new activity), and the current state is “final”, the subject should be “New activity on [date]”, and the body should contain a complete overview (therefore no changes).

These rules above are only to illustrate the problem. There are quite a lot of them (regarding combinations of status / date / time / etc.), about 500 lines of code in total.

The problem that arises is that this code is currently quite difficult to understand and maintain. New rules are introduced from time to time, and adding them without breaking other rules can be a pain. What would be the best way to rewrite such code into a more understandable and convenient code? Currently, the order of if-else branches is also very important. The first if statement is the most important, the next else-if statement is less important, until the last else clause for the most general case.

+3
source share
2 answers

It looks like something like an engine rule . Drools is one option, but it's almost certainly crowded!

Do you have an interface representing the rule? Sort of

public class Activity {}

public interface Rule {
     boolean applies(Activity);

     Activity applyRule(Activity x);
}

, , , .

Activity applyRules(List<Rule> rules, Activity);
+4

,

For all Rules
   if ThisRule.Applies(activity) then
       ThisRule.ApplyActions(email);
       break;

, Applies ApplyActions ConstructEmail - .

. .

, , , , , , .

, , , , , , , , , :

For all Rules
   if ThisRule.Applies(activity) then
       ThisRule.ApplyActions(email);
       if ThisRule.TerminalRule then
           break;

, , .

+2

All Articles