About Me

Hello, I'm an eclectic software professional working with enterprise software at SAP. This blog only contains my personal views, thoughts and opinions. It is not endorsed by SAP nor does it constitute any official communication of SAP.

Saturday, August 1, 2009

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.

No comments:

Post a Comment