For starters, take a look at this code:
def consume(food) if ! food.poisonous? eat(food) end end
What's wrong with it? The bang is barely noticeable! This is because it is essentially a thin line and most humans are trained to look for bangs at the end of a sentence, not in the middle. And not noticing the bang in this situation can prove deadly. I also find myself asking, "well, if it's not poisonous, than what is it?" So clearly this code does not "Say what I mean".
A better way to approach this method would be to remove the bang and add a more meaningful method to our food class. For example:
def consume(food) if food.edible? eat food end end
Not only is this approach more positive (thinking about edible food is always more enjoyable than thinking about poisonous food), but it clearly states our intent. This is white listing. Simply put, white listing is stating exactly what is allowed and denying everything else. In our case, we ONLY want to eat what is edible and nothing else. (more about white listing)
Moving on, how do you feel about this?
def consume(food) while ! food.gone? eat food end end
Let us assume that we cannot add another method on food that would allow us to add an inverse method to 'gone?'. Fortunately Ruby provides us with the "until" control structure. Let's try it out:
def consume(food) until food.gone? eat food end end
Once again, we've achieved a more readable and positive solution. I feel better already!
Now Debbie Downer has a friend, Miss Unless. Miss Unless is a temptress, so beware. At times you may find yourself wanting to use her in guard clauses and the like. To combat Miss Unless's seductions, use an 'if'. Stay positive and turn this:
def consume(food) eat food unless food.poisonous? end
into this:
def consume(food) eat food if food.edible? end
Ruby provides you with an extensive list of control structures, make sure you pick the ones that allow you to say what needs to be said clearly and positively.
No comments:
Post a Comment