Refactoring: Consolidate Duplicate Conditional Fragments; in Java, Python and Ruby

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.

Related posts:

  1. Playing with Ruby
  2. Ensuring the displaying of flash messages in Ruby on Rails
  3. NetBeans could make the Ruby on Rails experience great
  4. Distributed revision control was a breakthru
  5. Quick and dirty tabs on Ruby on Rails

About J. Pablo Fernández

http://pupeno.om
This entry was posted in tutorial and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre user="" computer="" escaped="">