Creating DRY Variables

In a recent blog post I read by Tom Dalling, I was introduced to the idea of never reassigning variables. This was part of a greater discussion on avoiding mutation in Ruby, but I wanted to focus on why just the act of setting variables once makes your code better.

For the better part of 4 months, the concept of DRY (Don’t Repeat Yourself) code has stuck with me whenever I’m writing Ruby code. If I am doing something more than once, it probably belongs in a method. Well in refactoring one of my recent projects, I noticed an annoying pattern. I was creating variables as nil, 0, or empty arrays to be set later in the method.

Usually this meant I was setting them inside a conditional or loop block. The reason I find myself doing this is because aside from instance or class variables, variables are only accessible from the block they are declared in. Variables are accessible to a block’s child though, so declaring the variable outside a loop or conditional allows me to set it inside and then use it again outside.

Scrolling through multiple methods and seeing this tells me my code isn’t DRY. I am repeating myself, not with identical lines of code, but rather in the repeated pattern of setting and resetting variables. There has to be a better way! Well there is.

I discovered today that you can use the returned value of a conditional or loop to set variables. What does this mean you might ask? Well often the conditional statements I write are written with the sole purpose of setting variables. Why not just return the output to the calling block?

discount_amount = 0
if customer.purchased_discounted_items?
discount_amount = 10
end

Traditionally the above is what I would write if I needed to set a variable inside a conditional statement. This can be boiled down to one line instead.

discount_amount = customer.puchased_discounted_items? ? 10 : 0

The above takes advantage of Ruby’s ternary operator, a shorthand for conditional statements.

Code that isn’t repetitive is easier to read. I am a firm believer in writing code that fixes repetition issues wherever possible. It often results in less code too. It’s easier for others or your future self to read if you have less code that does one thing in one place.