RSS
Facebook
Twitter

Tuesday, November 22, 2011

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…

Sunday, November 06, 2011

List executed code using PostSharp

This post was created to answer a question by Laimonas Simutis on the ALT.NET mailing list – how to list all executed code
There where many good ideas and your truly suggested using PostSharp – mainly because this is one of the examples I use in my AOP and PostSharp presentation. And so without further ado here is my solution for your consideration:

The “tracing” attribute

For this purpose I choose to use OnMethodBoundaryAspect which enable me to add hooks on method’s enter and exit:
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method, AllowMultiple = true)]
public class TraceMethodCallsAttribute : OnMethodBoundaryAspect
{
    private string _methodName;

    public override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo)
    {
        _methodName = method.DeclaringType.Name + "." + method.Name;
    }
    

    public override void OnEntry(MethodExecutionArgs args)
    {
        Console.WriteLine(">> {0}", _methodName);
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        Console.WriteLine("<< {0}", _methodName);
    }
}
This is your simple method boundary aspect which is good to add custom functionality before and after method call as well as on exception and/or successful completion. This time I only needed the enter and exit functionality.
My attribute has several attribute of it’s own, one simple for serialization and the other is where the magic happens – the MulticastAttributeUsage that tells PostSharp that this attribute should be automatically applied to every method in the class or assembly.
Other than that I’ve also used CompileTimeInitialize in order to save some cycles by “calculating” the method name only once (at compile time) instead of each time the method is called.

Using the attribute


Now all I have to do is add this line to the AsseblyInfo.cs file:
[assembly: TraceMethodCalls]
And that’s it – running the following program:
class Program
{
    static void Main(string[] args)
    {
        var a = new A();
        for (int i = 0; i < 3; i++)
        {
            a.MethodOne();
            a.MethodTwo();
        }
    }
}

public class A
{
    public void MethodOne()
    {
        Console.WriteLine("I am in method one");
    }

    public void MethodTwo()
    {
        Console.WriteLine("I am in method two");
    }
}
Provides the desired resultimage

Happy coding…
Related Posts Plugin for WordPress, Blogger...