Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best design pattern for structured sequential handling

Doing maintenance on a project I came across code, which I find unnecessary hard to read and I wish to refactor, to improve readability.

The functionality is a long chain of actions that need to be performed sequentially. The next action should only be handled if the previous action was successful. If an action is not successful a corresponding message needs to be set. And the returned type is a Boolean. (successful true/false). Just like the return type of all the called actions.

Basically it comes down to something like this.

string m = String.Empty; // This is the (error)Message.
bool x = true; // By default the result is succesful.

x = a1();
if(x) {
    x = a2();
}
else {
    m = "message of failure a1";
    return x;
}

if(x) {
    x = a3();
}
else {
    m = "message of failure a2";
    return x;
}

//etcetera..etcetera...

if(x){
    m = "Success...";
}
else{
    m = "Failure...";
}

return x;

My question is: What is a better structure / pattern to handle this kind of logic?

Main goals are:

  • increase readability.
  • increase maintainability.

Please keep in mind that it is quite a large chain of actions that is being performed sequentially. (Thousands lines of code)

like image 332
Tony_KiloPapaMikeGolf Avatar asked Aug 17 '26 22:08

Tony_KiloPapaMikeGolf


1 Answers

Make a list of action/message pairs:

class Activity {
    public Func<bool> Action { get; set; }
    public String FailureMessage { get; set; }
}

Activity[] actionChain = new[] {
    new Activity { Action = A1, FaulureMessage = "a1 failed"}
,   new Activity { Action = A2, FaulureMessage = "a2 failed"}
,   new Activity { Action = A3, FaulureMessage = "a3 failed"}
};

A1..A3 are no-argument methods returning bool. If some of your actions take parameters, you can use lambda expressions for them:

Activity[] actionChain = new[] {
    ...
,   new Activity { Action = () => An(arg1, arg2), FaulureMessage = "aN failed"}
,   ...
};

Now you can go through the pairs, and stop at the first failure:

foreach (var a in actionChain) {
    if (!a.Action()) {
        m = a.FailureMessage;
        return false;
    }
}
m = "Success";
return true;
like image 120
Sergey Kalinichenko Avatar answered Aug 20 '26 14:08

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!