Optional parameters flag arguments in disguise

July 7, 2011

While working in a recent code base I’ve noticed a interesting side effect to the introduction of C# 4 (which now has optional parameters) to the team.

I’ve noticed a few methods that look like this ……

public int Calculate(
    IEnumerable<int>; x, 
    IEnumerable<int>; y = null)
{
    if(y != null) {
        // Calculate with x and y
    } else {
        // Calculate with x
    }
}

I don’t like this type of method for a few reasons…

  • They do more than one thing and therefore break principles of single responsibility
  • They increase complexity by adding a branch that can be eradicate by separation
  • They are difficult to name becasue it may do two things that are hard to represent in the name

Normally you’d spot this type of method because it would be used in places with a null as the second parameter. By adding optional parameters it makes it less obvious to spot the hidden complexity. I’d normally deal with these methods by breaking them into two methods and naming them better.

Martin Fowler recently wrote a much better piece about Flag Arguments which is worth reading!