Wednesday, March 02, 2005

Optional Parameters

Over at Code Project there is a new poll about peoples opinions of Optional Parameters. I for one have always tried to avoid them at all costs, due more to a bad feeling than any good reason. Anyway, some of the arguments over there got me thinking:

Why don't I like optional parameters

After a sleepless night of debate with myself, I've come to the conclusion that I still don't like them.

The reason is simple. Method Overloading, or passing an object (the properties represent the parameters) can be just as effective as using optional parameters. I feel that this feature is really something that is not needed, and possibly has the ability to create less understandable code.

Less understandable... yes, by this i mean a situation where a method changes it's behaviour based on an optional parameter. This is a situation where a required enumeration specifying the exact operation to perform would be much better, and the code would be much easier to understand. An example is below:


Sub Main()
Round(1.23, False)
Round(1.45)
End Sub

Function Round(ByVal value As Double, Optional ByVal down As Boolean = True) As Integer
'... perform rounding
End Function
As opposed to this:

Public Enum RoundingOperation
Up
Down
End Enum

Sub Main()
Round(1.23, RoundingOperation.Down)
Round(1.23, RoundingOperation.Up)
End Sub

Function Round(ByVal value As Double, ByVal operation As RoundingOperation) As Integer
'... perform rounding
End Function
Sure it's more typing, but the code as far as I'm concerned is much more self documenting. Let me know your thoughts...

No comments: