1

I was coding an if-then-else, when it occurred to me, that this was a bad programming:

state = "published" # state could be "published" or "draft"

...

if state == "published"
  display_production_copy
else 
  display_draft_copy
end

However, as I was coding this function, it occured to me that I should have written this

state = "published" # state could be "draft"

...

case state
when "published"
  display_production_copy
when "draft"
  display_draft_copy
else
  fail "Invalid state: #{state}" # throw an exception
end

This way if someone added a different state for example:"reviewing" and the programmer didn't get to "update" this method, then incorrect programming would have been run.

I suspect that in all cases where there is a explicit set of values, other than TRUE or FALSE, all if-then-[elseif]-else comparisons should be done via case [switch] and must come with an else that throws an exception.

Is this defensive programming? or paranoia?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Daniel
  • 7,006
  • 7
  • 43
  • 49
  • Just because you're paranoid doesn't mean they aren't out to get you! :) On a serious note, I think it would depend on the situation. I had a similar situation with a project I had at work regarding OS commands, and I decided to go with a model that matched your second example. In this situation I'm glad I did, as the devs who used it tried to use other commands that they never identified ahead of time and had to be handled in their own unique way. This stopped their behavior with a big red flag (literally) so we knew what had to happen right away – Taegost Feb 01 '16 at 20:42
  • Indeed; the argument is probably even stronger if you're talking about a compiled or otherwise inspected-in-advance language with sufficiently strong types that it can refuse to build or run if there are any `case` statements that don't hit all of the required cases. Then if somebody extends the potential members of a set they immediately get told to finish the job rather than it turning out much later when somebody happens to hit a particular part of the code that they didn't think the thing through. – Tommy Feb 01 '16 at 20:47

0 Answers0