Refactoring conditionals to strategies (in .Net/C#)

Published on December 02, 2019

I’m doing some work on a legacy code base and there are some common refactorings I do over and over. One of my favourite improvements is making long lists of conditionals easier to read and especially test.

I use the common refactor-to-strategies pattern from Martin Fowler to deal with these.

The original code and issues with it

Here is a simplified example of what the code typically looks like. There are heaps of problems with code like this. Especially when it’s just a tiny part of an enormous 10,000 line file!

I had a new junior engineer ask how best to tackle something like this. Here is what I told them.

  • Hungarian notation is hard to read, the prefix has no value in a strongly typed language, the actual type drifts from the original prefix over time. We should remove the prefixes.
  • Using Area and Area2 do not tell us what they are actually used for. Why is 2 different from the original one? We should name these properly if we can.
  • There is repetition in the sanitization. We should prevent this.
  • It’s difficult to test long conditionals. We should make it easier to test.
  • It’s difficult for a new dev to understand and modify this code. We should always make it easy to modify the code.
  • Because the conditionals are different, all of these might run but they all assign to the same variable. It doesn’t matter too much here because it’s just assignments but we should make it so that only one of these will run as a matter of good practice.
pubic partial class MovementMain: Page
{
  // ... a few thousand more lines of code
  if (strArea2.ToLower().Contains(" container"))
  {
    strMovementGroup = strArea2.Replace(" Container", "").Replace(" container", "");
  }
  else if (strArea.ToLower().Contains(" container"))
  {
    strMovementGroup = strArea.Replace(" Container", "").Replace(" container", "");
  }
  else if (intStatus == 3 && "Vehicle".Equals(strTransportType) && intRealQty == 0)
  {
    strMovementGroup = "Vehicle";
  }
  // ... a few thousand more lines of code
}

Refactored code and comments

I created an interface to describe the condition used to select a strategy and the specific strategy to use when selected.

The strategies are added to a list in the desired precedence order.

I then use linq to select the first applicable strategy and use its result.

There is more code here because of the interface and boilerplate around each class. But it’s much easier to understand and test (imho anyway!).

If a new developer needs to add a new condition here they just need to add a new condition to the list.

We don’t need to test if linq works. We have moved the business logic out of the aspx.cs page. If we did need to test the selector choosing we could move that to factory of some kind.

I also renamed all the variables so they make a little bit more sense.

I don’t show it here but the strMovementGroup value is later used in further conditionals. Now that we have a strategy selector we can also put the items that depend on this value in the strategy. The root conditional is the one that selects the strMovementGroup. This is really important for future refactoring.

I added an ‘empty’ strategy so we don’t have to worry about nulls.

pubic partial class MovementMain: Page
{
  // ... a few thousand more lines of code
  var movementGroupSelectors = new List<ICondition>()
  {
    new VehicleSelector(intStatus, strTransportType, intRealQty),
    new MovementSelector(strArea),
    new MovementSelector(strArea2),
    new UndefinedSelector()
  };

  var movementGroupSelector = movementGroupSelectors
    .First(selector =>
    selector.IsApplicable());

    strMovementGroup = movementGroupSelector.SanitizedName();
 // ... a few thousand more lines of code
}



  // The following would be in different files
public interface ICondition
{
    bool IsApplicable();
    string SanitizedName();
}

public class MovementSelector : ICondition
{
    private readonly string movementName;
    public MovementSelector(string movementName)
    {
        this.movementName = movementName;
    }
    public bool IsApplicable()
    {
        return movementName.ToLower().Contains(" container");
    }
    public string SanitizedName()
    {
        return movementName.Replace(" Container", "").Replace(" container", "");
    }
}

public class VehicleSelector : ICondition
{
    public static string VEHICLE_NAME = "Vehicle";
    public static int AVAILABLE_STATUS = 3;
    private readonly int activeStatus;
    private readonly string transportType;
    private readonly decimal realQuantity;
    public VehicleSelector(int activeStatus, string transportType, decimal realQuantity)
    {
        this.activeStatus = activeStatus;
        this.transportType = transportType;
        this.realQuantity = realQuantity;
    }
    public bool IsApplicable()
    {
        return activeStatus == AVAILABLE_STATUS && transportType.Equals(VEHICLE_NAME) && realQuantity == 0;
    }
    public string SanitizedName()
    {
        return VEHICLE_NAME;
    }
}

public class UndefinedSelector : ICondition
{
    public bool IsApplicable()
    {
        return true;
    }
    public string SanitizedName()
    {
        return string.Empty;
    }
}

Now sometimes this much refactoring will be overkill.

This happened to be an area where new conditions are likely. You have to use your own judgement to decide what is worth refactoring or not!

Darragh ORiordan

Hi! I'm Darragh ORiordan.

I live and work in Sydney, Australia building and supporting happy teams that create high quality software for the web.

I also make tools for busy developers! Do you have a new M1 Mac to setup? Have you ever spent a week getting your dev environment just right?

My Universal DevShell tooling will save you 30+ hours of configuring your Windows or Mac dev environment with all the best, modern shell and dev tools.

Get DevShell here: ✨ https://devshell.darraghoriordan.com


Read more articles like this one...

List of article summaries

#engineering

Building an AI generated game with Stable Diffusion and data from Wikipedia

Last week I released a game called Doodle:ai.

In the game you’re shown AI generated images and you have to guess the Wikipedia topic it used to create the game.

#engineering

Easiest way to optimise images for web

Here is how I optimise all pngs and jpgs in a folder for publishing to the web.

#developer-experience

Start tracking DORA metrics for your team in just 15 minutes with Apache Dev Lake

DORA (DevOps Research and Assessment) metrics are an excellent way for engineering organisations to measure and improve their performance.

Up until now, monitoring the DORA metrics across Github, Jira, Azure Devops etc required custom tooling or a tedious manual process.

With Apache Dev Lake you can get beautiful reporting for DORA metrics on your local machine in as little as 15 minutes (honestly!).

From Google Sheets to Grafana
From Google Sheets to Grafana

#engineering

A summary of NDC Sydney 2022 Developer Conference

I attended my first in-person conference for more than 3 years last week! NDC is one of the more well-known developer conferences in Australia and New Zealand. It’s a 5 day conference with 3 days of talks and 2 days of workshops.

There’s so much to learn across all the streams so I try to take notes for each of the talks to quickly reference them later. This post contains all my notes. I’ll add the relevant videos to talks later if they’re released.

A reminder that these notes are just my notes. They’re paraphrased and summarised from what the speaker actually said. Each speakers would have provided must more clarity and went into more detail during their pressos!

Comments