Monday, 18 May 2009

Extension methods make your code more readable

There has been a long standing argument for and against using extension methods. Recently I am on the quest to write code which is as readable as possible. That really is my prime aim - I want someone who is simply scanning my code to be able to, at a high level, understand exactly what is going on in that function. All other aims come second to that (e.g. until a requirement comes along which says otherwise).

Well, six months ago, I would never have made this statement - "Extension methods are a massive help here!". Honestly, they just are. I know people hate them because you can't really tell where the method comes from, and it looks wierd, and it breaks OO because you should inherit to add functionality (well actually, I disagree with that statement being made blindly)...

So I have a function which takes in some dates and returns a status depending on how the dates compare. Here is a simplified version of the function:

public Status GetStatus(DateTime now, DateTime modifiedOn, DateTime createdOn)
{
  if (modifiedOn.Date == now.Date)
    return Status.Amended;
  else if (createdOn.Date == now.Date)
    return Status.New;
  else
    return Status.Unchanged;
}

So what's wrong with that? Well you have no idea what the if statement is actually doing! Tell me, if you scan that quickly, can you tell what the business rule is here? I am pretty sure most people will have to scan that a few times to get what is going on there. I considered adding a comment, but comments are a definite code smell (see DRY) so this is how I changed it (using an extension method)

public Status GetStatus(DateTime now, DateTime modifiedOn, DateTime createdOn)
{
  if (modifiedOn.SameDayAs(now))
    return Status.Amended;
  else if (createdOn.SameDayAs(now))
    return Status.New;
  else
    return Status.Unchanged;
}

Simple but effective methinks. I think it's definitely clearer (though could perhaps be made even better). Do you agree?

1 comment:

James Norton said...

I couldn't agree more. I use this pattern in my JavaScript code all of the time. Its an excellent way of making code easier to read and more self documenting.