Refactoring Ruby on Rails

Ruby on Rails / Refactoring – null object pattern

Ruby on Rails / Refactoring – null object pattern January 22, 20183 Comments

Null Object refactoring pattern jumps into action when we have cases where we are checking if given object is present and if it’s not then we are returning the default value for given attributes or methods. It usually requires from us to use if condition which makes code a little bit less readable and a little bit harder to test – with Null Object pattern code is very simple and easy to test.

To better demonstrate advantages of using Null Object pattern let’s consider following case: we have two classes, User object which operates on Post class.

class User < ActiveRecord::Base
  has_many :posts
  
  def latest_post_title
    post = posts.order('created_at DESC').first
    
    if post.present?
      post.title
    else
      "No posts yet"
    end
  end
end

It’s far from single responsibility principle - we are doing a few actions here:

1. We fetch newest post
2. We are checking if post is present
3. We are displaying post title if post is present
4. We are displaying proper information when post is not present

This is the time when Null Object comes in. Let’s create our new object first:

class NoPost
  def title
    "No posts yet"
  end
end

It’s just a plain Ruby object with simple logic. Now it’s time to refactor our User model by doing a couple things:

1. We will move query to separated method
2. We will move latest post assignment to separated method using NoPost Null Object
3. We would simplify method responsible for returning latest post title

After implementing all of these points, our User class is way cleaner and more readable:

class User < ActiveRecord::Base
  has_many :posts
  
  def latest_post_title
    lastest_post.title
  end
  
  private
  
  def latest_post
    find_latest_post || NoPost.new
  end
  
  def find_latest_post
    posts.order('created_at DESC').first
  end
end

The contents of our User#latest_post_title method is obvious now and we get rid of if condition. It’s also very important to name our Null Object properly so its name reflects the idea behind it.

Have problems with refactoring of your Ruby on Rails application?

Hit me on twitter or use contact form and let me know how can I help you!

Image source: Photo by Porapak Apichodilok from Pexels https://www.pexels.com/photo/blank-female-hands-lady-388898/

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

3 comments

    1. Hello Jesus! Very nice article, I had a feeling that you wrote everything about nil (as always when you write about something) 🙂

Leave a Reply

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