In BlogPost, Ruby

Refactoring If Statements Out of Your Ruby Code

As I kept writing more code, I found I didn’t like conditionals all that much, especially when they started to obscure the purpose of the code. A technique I found from this blog post is described below.


Why would you want to refactor?

I wanted to refactor to clean things up and make it easier to add new features going forward. Too much conditional logic (and nested logic) forces me to spend more time reasoning about code than I want to.

When would you want to refactor?

It’s really a personal choice. In a startup environment where things move fast, I tend to refactor in small bits in order to make it just a bit easier for someone else going forward.

I also tend to feel more comfortable refactoring when there is a robust test suite surrounding the code. This way you’ll know if your refactoring breaks something.

Example: Reasons for Unsubscribing from an Email List Code

Here’s a somewhat contrived example of conditional code loosely based on something I saw in production:

Step 1: Build a collection of reasons

We build a collection of UnsubscribeReason classes housed by an UnsubscriberReasons class.

Step 2: Build a reason class for the reason classes in Step 1 to inherit from

We build the parent class for the collection of classes in Step 1.

Step 3: Build the actual UnsubscribeReason classes

Now we build the actual UnsubscribeReason classes. You’ll notice they have an introspection property has_reason? that expects an OpenStruct with a reason_types property so we can check whether a specific “unsubscribe reason” such as too many emails exists.

Step 4: Build a factory to fetch the reasons

Next we build a collection of UnsubscribeReasons that includes the classes that map to the various reasons a user unsubscribed.

Step 5: Build a reasoner class to house the reasons

Finally, we build an UnsubscribeReasoner class with a reason list to house all the valid unsubscribe reason we found.

Step 6: Refactor the conditional code to use our new classes

Maybe it’s a bit too contrived

The nice thing about the above refactoring is that if we want to add another unsubscribe reason, we more or less just have to add a class. The code is a bit longer, but I’ve been using contrived example code so saying the code is longer is a bit of an unfair statement.

You’ll have to try and see what works for you.


Overall, this is an attempt to show how you can refactor conditional logic out of your Ruby code. The example repository containing all this code is here.

Recent Posts
elixir basicselixir basics