Posts

Showing posts from August, 2009

Optional Parameters and Method Overloads

The ability to declare optional parameters is another feature that will be introduced in C# 4.0. A natural complement to method overloads, it generally helps code to be more concise. Until now, method overloads have been used for the awkward responsibility of creating default values for what otherwise would be much better expressed as optional parameters. Many overloads have been created for which the sole responsibility is to call another overload with some default values for some parameters. public CreditScore CheckCredit() { return CheckCredit(false, true); } public CreditScore CheckCredit(bool useHistoricalData) { return CheckCredit(useHistoricalData, true); } public CreditScore CheckCredit( bool useHistoricalData, bool useStrongHeuristics) { // do the heavy-lifting ... } For this style of method, optional parameters let you create just one method, with default values set on its signature. public CreditScore CheckCredit( bool useHistoricalData = false, bool u

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 param