Named Parameters Increase Readability

When reading C# code, sometimes there are method calls which aren't readily obvious. The method can have too many parameters, or a series of parameters of the same type. This can make things a little confusing. A more aggravating case is that of boolean parameters. It's hard to find out what true or false mean in some cases.

var creditScore = customer.CheckCredit(false, true);

Normally, we need to look at the method signature to understand how it's being called, and what each parameter represents.

public CreditScore CheckCredit(
  bool useHistoricalData, bool useStrongHeuristics) {
  ...
}

Since code is more often read than it's written, any means to improve readability will have a direct effect on maintainability. Every line of code should clearly communicate its intent. No clever hacks or streams of unintelligible parameters.

A good solution to the boolean case is to use enumerations. This way, we force the caller to use a well known name for the parameter value.

var creditScore = customer.CheckCredit(
  HistoricalData.None, Heuristics.Strong);

Named parameters are a good solution to this general problem (not just for booleans). C# 4.0 introduces them into the language, so that parameter names can be used when calling a method. The method definition doesn't change.

var creditScore = customer.CheckCredit(
  useHistoricalData: false, useStrongHeuristics: true);

Whenever a method call is not understandable, naming the parameters in the call should help.

Comments

Popular posts from this blog

The Acyclic Visitor Pattern

Some OO Design

NRoles: An experiment with roles in C#