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

You may also like:

Hi, I'm Pablo, this is my web site. You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 4,048 other subscribers

I'm writing a book

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I've been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git ham radio history idea Java Keep on Posting Kubuntu Lisp Non-Fiction OpenID programming Python Radio Society of Great Britain Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek startups technology Ubuntu web WordPress

I've been writing for a while:

Mastodon

%d bloggers like this: