Saturday, December 30, 2006

C# Nitpick

A lot of modern languages supports optional parameters, or parameters with default values. I've read in this article that .net actually supports them, but for some inane reasons, the C# designers did not build support for it. The article mention something about optional arguments being just syntactic sugar that can be emulated using overloaded methods. This might be true, but the code you have to write to do this workaround is usually too much, and quite frankly just silly.

Consider constructors. It's true you can write overloaded constructors anyway, but what if I have to do some initialization that's quite involved? What I usually do in these cases is that I create a private CommonInit() method to handle the involved initializations, and the constructors call to it as it's first, and usually only, line of code. Here's an, admittedly, contrived example:

class Contrived
{
public Contrived(int maxLines)
{ _maxLines = maxLines; }
public Contrived()
{ _maxLines = 5; }
private int _maxLines;
}

In the example above, using the parameterless constructor actually provides a default value of 5. Imagine if prior to assigning to _maxLines, we have to do more stuff, whatever they are. Where do you put this code? This is usually what I do:

class Contrived
{
private void CommonInit(int maxLines)
{
// involved code here
_maxLines = maxLines;
}
public Contrived(int maxLines)
{ CommonInit(maxLines); }
public Contrived()
{ CommonInit(5); }
private int _maxLines;
}

Looks ok, but imagine if default values are supported: we won't have to go through all this hoops just to support multiple ways of constructing the object from this class. Had optional arguments been supported, things would be this clean:

class Contrived
{
public Contrived(int maxLines = 5)
{
// involved code here
_maxLines = maxLines;
}
private int _maxLines;
}

See how short and concise it is now? Here's hoping that later versions of C# will support this type of declarations. Having to do all those CommonInits for all my classes that I want to be constructed in various ways consumes more time that I'm willing to waste working around 'syntactic sugars', or lack of it.

No comments: