Optional parameters flag arguments in disguise
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 break Single Responsibility Principle.
- They are complex. I need an if statement to decide on which branch should be performed.
- They are less expressive about what they do.
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 you should read!