Tuesday, June 2, 2009

Optional Params Anyone?

During my break today, I was able to skim on some articles about the upcoming C# 4.0. Pretty much everything is evolutionary but one feature stands out from the rest not because it’s revolutionary but because it’s needless and counterproductive. The C# team decided to add optional parameters support to C# ala VB. I’m not a fan of optional parameters and as a matter of fact, I abhor it like Dijkstra abhorred GOTO. It undermines the benefit of overloading. To stretch my point, let’s say you have a class Timer with alarm features and with the following overloads:

public void Start(DateTime startTime)
{
// more codes here
}

public void Start(DateTime startTime, TimeSpan elapsedTimeBeforeAlarm)
{
// If elapsed time is 0 or less, throw invalid argument exception
}

public void Start(DateTime startTime, DateTime alarmTime)
{
// If alarm time is prior to start time, throw invalid argument exception
}

As you can see, each method has distinctive purpose and logic based on their parameters. The first one does not set the alarm whereas the other two sets them but through different means based on the type of the second parameter.

A novice programmer can easily think of optional parameters to implement all of these. He could come up with something like this instead:

public void Start(DateTime startTime, TimeSpan elapsedTime=”0:00:00:00”
, DateTime alarmTime=DateTime.MinValue)
{
// Determine what combination and execute logic accordingly
// In addition, validation is also performed to the parameters

}

Wow! One method to serve them all! Nothing’s cool about this unfortunately. First of all, it’s fat because it’s no longer cohesive. The codes which check for the combination of the parameters supplied do not have anything to do with setting the alarm anymore. It’s difficult to maintain these convoluted codes. I’m not saying that this kind of coding is rampant but hey, it could happen.

Microsoft promised that the new incarnation of the .NET Framework will be a “real upgrade”. It will contain less new classes and more upgrades to existing ones. What I don’t expect are fixes for things which ain’t broke, let alone those that promote bad practices. Optional parameters is in that list. I just hope it’s the only one.

No comments:

Post a Comment