lundi 1 février 2016

defensive programming, if-then-else should be a case [switch]?

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 then all comparisons should be done via case [switch] and must come with an else that throws an exception.

Is this defensive programming? or paranoia?

Aucun commentaire:

Enregistrer un commentaire