Enumeration Rumination

I now interrupt this blog with two things I'd like to talk about with respect to enumerations.

The first one deals with method arguments and booleans. Take a look at this code:


So, can you tell me what Build() does? Other than build something?

How about this:


This reads easier. You know that Build() has something to do with files and directories and so on. Now, I know, you'll probably counter with, "are you kidding me? change all my method arguments that are booleans to enumerations?" Enumerations give you a bit more flexibility as you can add more values in the future if need be without having to change the signature, and they provide more information in the code. I'm not saying you should change all your method signatures, but give this idea some thought in the future.

Speaking of adding enumeration values...I just found out there's an exception in .NET called InvalidEnumArgumentException. You may want to use it in the default section of a switch statement:

public static Beer Create(Manufacturer manufacturer)
    Beer beer = null;

        case Manufacturer.Newcastle:
            beer = new Newcastle();
        case Manufacturer.Duff:
            beer = new Duff();
        case Manufacturer.Blatz:
            beer = new Blatz();
            throw new InvalidEnumArgumentException();

    return beer;

Enumerations...so quirky...yet so useful...sometimes.

* Posted at 05.19.2009 11:21:39 PM CST | Link *

Blog History