Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 903
swampsjohn Avatar asked Mar 19 '10 01:03

swampsjohn


Video Answer


2 Answers

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.

like image 80
Michael Petrotta Avatar answered Sep 19 '22 12:09

Michael Petrotta


I find 'can never happen' sounds good until it bites you in the ass months later, after a colleague has added code, breaking your original code. So, for myself, I would make sure my if 's are solid even if it seems impossible.

like image 26
Kevin Avatar answered Sep 17 '22 12:09

Kevin