I’m reading the book Refactoring and one of the refactorings it shows is called “Consolidate Duplicate Conditional Fragments” and it shows an example in Java:
if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); }
is refactored into
if (isSpecialDeal()) { total = price * 0.95; } else { total = price * 0.98; } send();
If you do it in Python it’s actually quite similar:
if isSpecialDeal(): total = price * 0.95 send() else: total = price * 0.98 send()
is refactored into
if isSpecialDeal(): total = price * 0.95 else: total = price * 0.98 send()
But in Ruby it’s different. In Ruby, like in Lisp, everything is an expression, everything has a value (maybe there are exceptions, I haven’t found them). Let’s look at it in Ruby:
if isSpecialDeal() total = price * 0.95 send() else total = price * 0.98 send() end
is refactored into
total = if isSpecialDeal() price * 0.95 else price * 0.98 end send()
Or if you want it indented in another way:
total = if isSpecialDeal() price * 0.95 else price * 0.98 end send()
We can push it one step further:
total = price * if isSpecialDeal() 0.95 else 0.98 end send()
Of these three languages, only Ruby can manage to have inside each branch of the if only what changes depending on the condition and nothing else. In this simple case you could use the ternary operator, :?, but if the case wasn’t simple, Ruby would be at an advantage.
I’m reading Refactoring: Ruby Edition next.
Leave a Reply