Do not use boolean method parameters

What!? Why not!?

The declaration of a method with a boolean parameter looks simple enough, what could be wrong with it?

void Dispose(bool disposing) { ... }

The problem is not in the declaration (I picked this example because it is horrible in more ways than one), it is in the readability of the calling code.

obj.Dispose(true);

It is not immediately obvious what this true means.Even if the method name had some meaning in it, it would still probably be vague at best.

A solution to this would be to make explicit what the boolean represents. That could either mean that you make two methods, one that behaves as if the boolean was false and one that behaves as if the boolean was true.

Another option is to create an enum that gives you two names to work with:

public enum DisposeOptions
{
    DisposeManagedAndUnmanagedResources,
    DisposeUnmanagedResourcesOnly
}

True, it is a bit more work, but it reads so much better when you see the calling code:

obj.Dispose(DisposeOptions.DisposeManagedAndUnmanagedResources);

There is no guessing what this does, is there.

Of course there may be exceptions. One I can think of is when the method name clearly explains the purpose of the boolean parameter – the only parameter for the method – this goes south with multiple parameters.

Enable(true);

Not something you would write in C# perhaps, but valid for C++.

The goal is to create code that reads nice, something you can understand when you saw it for the first time (or revisit it after 6 months). Arguments that it’s too much typing are completely invalid in my opinion. You read that code way more often than you write it, so make that a nice experience.

 

Leave a Reply

Your email address will not be published. Required fields are marked *