language-agnosticconditional-statements

Should you always write code for else cases that "can never happen"?


Take some code like

if (person.IsMale()) {
    doGuyStuff();
} else {
    doGirlStuff();
}

Should this be written to explicitly check if person.isFemale(), and then add a new else that throws an exception? Maybe you're checking values in an enum, or something like that. You think that no one will add new elements to the enum, but who knows? "Can never happen" sounds like famous last words.


Solution

  • I think you've answered your own question. If you know you're never going to see additional values:

    bool isSet = ...
    if (isSet)
    {
        return foo;
    }
    return bar;
    

    ...then don't bother. But if there's a chance there could be more than two possible values, cover yourself. You (or the maintenance programmer two years down the road) will be grateful for it.