Almost a month ago I was out at a client waiting for some feedback from a few meetings and got into a discussion with another developer about default parameters. I decided to bring the discussion to Twitter and Facebook to hear some more opinions. Here is a quick write-up 🙂
The following bit is a summary of the discussion, I also had a read on the four-part blog post by Eric Lippert which of course added further to the discussion. If something is missing or incorrect, please let me know.
Introduced when, and why
Optional arguments, also referred to as default parameters, were introduced with C# 4, and as one dev put it ‘I use them but always feel a little dirty afterwards.’ I can relate, and optional arguments have caused a few debates. I was surprised to see that the majority of the devs that replied to the Tweet gave the thumbs up,- there is nothing wrong with using them as long as you take some precautions. And after seeing the replies, I now agree. This was a highly requested language feature that would let us avoid overloading of methods, and therefore have less code to maintain and hopefully introduce less defects.
Optional arguments help us avoid a long list of overloaded methods. You can extend an existing method by adding some arguments that have default value instead of writing an identical method with different parameters. This is also where you want to be careful if you decide on either changing the default value in a library or adding optional arguments in a method to an existing library. It’s also good to keep in mind that if your method has many optional arguments it might be doing too many things, which indicates that you need to look over your code and break things down into tinier pieces. (Use of flags is also a good indicator that there might be a better way to solve that particular problem, but that is a different discussion).
Optional arguments also have a peculiar behavior when used with interfaces. Even if you have specified a default parameter in the interface, you can ignore it on the class that implements the interface. If you have two interfaces that both define the same method with the same default parameters but different values you would need to access the method through the interface and the method that has the value you want to be used (- I didn’t know about this before I read Eric’s blog series on the topic, he has some example worth checking out).
On a side note
Optional arguments should not be confused for the param arrays (allows you to pass n number of arguments to a method)- we are talking about two completely different things and it is important to understand the difference. If you don’t know how many arguments the user will pass in, use a param array, if you need to set default values, use optional arguments. If you need both, use both, but you cannot set a default value for a param array in the method declaration.