Avoiding Overloads? Part 2

I’d like to address several of the comments to my last post:

Maybe it’s me, but I can’t see the circumstances in which a user of your method would want to call Decide(sideA).

But it does make sense to me to allow one or both arguments to be null: the caller of your method may have object references and not know or care if they are null.

I’m sorry many people misunderstood my example, partially, I admit, because it wasn’t that good.
Let’s take another example: The ICodeGenerator.GenerateCodeFromCompileUnit Method.
In this case, I have to send three parameters. The last one is of type CodeGeneratorOptions and can be null.
However, I would not have known this, have I not looked in the docs, would I?
This is one of the cases where an overload sans the last parameter would have been useful.

And no, default values are not the case either, using a Win32 example, CreateFile(“test.txt”) is not easier to read than CreateFile(“test.txt”, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); Forcing programmers spell out the options they want makes the code more readable, since you don’t have to go through the docs to look up the defaults.
– Jerry Pisk

Jerry, I think you’re getting this the other way around.
If you’re sure you want to get things right, yes, you can use the second option. However, if you know that all you need is a file that would be created, always overriding and would have normal attributes, you would call the first version, since you can deduce these are the defaults for the operation or might even not care.
Besides, this would cause huge method calls in your code, thus making it less readable.

One last thing I wanted to reiterate was that this is not the case when dealing with unknown input. If I knew there were always two parameters retrieved from the user and sent directly to the method, I would go with the two parameters approach and be done with it.
However, what I was talking about referred to when you have other methods calling your method with their own data and logic. This is the case when you would want to do something like this.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s