.NET

Refactor “if” statements – functional programming style

Have you ever seen code that look like this:

public string GetStatusDescription(Model model)
{
    if(model.HasProblemReports)
    {
        return "Errors";
    }
    if(model.SystemState.WorkingMode == WorkingMode.NotManaged)
    {
        return "Manual";
    }
    if(model.SystemState.IsInitializing)
    {
        return "Initialize";
    }
    if(!model.SystemState.InService)
    {
        return "Not in service";
    }
    if(model.SystemState.WorkingMode == WorkingMode.Paused)
    {
        return "Paused";
    }
    if(model.Storage.Objects.Any(obj => obj.IsMoving))
    {
       return "Movement in storage";
    }
    return string.Empty;
}

I know I have – yesterday, I’ve changed the variable names and removed a bit of plumbing code but in essence this is a real function I had to work with.

The problem with this kind of code that it start out simple but quickly becomes hard to read and maintain. Because the ordering of the “if” statements matters as much as the condition itself.

One solution is to use the well known Chain of Responsibility pattern. although it would probably work in this case, I’ve noticed that developers shy from using it in code similar to this example. It’s as if they feel that they “waste” good code by creating a”whole class for two lines of code”. Another reason not to use CoR is that in this case I don’t want to encapsulate the logic of this method in a lot of classes – I just want to be able to easily understand what the method does and add/remove/update it easily.

I literally felt pain writing each new “if” statement until I could take it no more and so I’ve decided to refactor it.

First I’ve created a class to hold each condition:

class ModelToMessage
{
    private Func<Model, bool> _predicate;
    public ModelToMessage(Func<model ,="" bool=""> predicate, string message)
    {
        _predicate = predicate;
        Message = message;
    }
    public bool IsValid(Model model)
    {
        return _predicate(model);
    }
    public string Message{get; private set;}
}

Using this new class I was able to declare the following list and refactor my method:

private List<modeltomessage> _messageCreators = new List<modeltomessage>
    {
        new ModelToMessage(model => model.HasProblemReports, "Errors"),
        new ModelToMessage(model => model.SystemState.WorkingMode == WorkingMode.NotManaged, "Manual"),
        new ModelToMessage(model => model.SystemState.IsInitializing, "Initialize"),
        new ModelToMessage(model => !model.SystemState.InService, "Not in service"),
        new ModelToMessage(model => model.SystemState.WorkingMode == WorkingMode.Paused, "Paused"),
        new ModelToMessage(model => model.Storage.Objects.Any(obj => obj.IsMoving), "Movement in storage"),
        new ModelToMessage(model => true, string.Empty),
    };
public string GetStatusDescription(Model model)
{
   var messageCreator = _messageCreators.First(mc => mc.IsValid(model));
    return messageCreator.Message;
}

The last item on the list is the “default” item that is always true and return an empty string.

I really like the fact that it’s easy to understand which message comes before which message and it’s easy to add new conditions and change their priority.

Happy coding…

References: Refactor “if” statements – functional programming style from our NCG partner Dror Helper at the Helper Code blog.

Related Articles

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ashok Guduru
Ashok Guduru
9 years ago

But don’t you think this new code unnecessarily checking all the conditions even after one is satisfied?

Back to top button