Single Purpose Methods in Ruby

Methods in Ruby should have a single purpose and a descriptive name. Short, single purpose methods are self documenting and easier to test and reuse throughout the codebase. Let’s start with an example of a bad method that has multiple responsibilities:

def popular_comments_array
  comments = Comment.all
  comments = comments.select { |comment| comment.likes > 40 }
  result = []
  comments.each do |comment|
    result.push({ title: comment.title, body: comment.body })
  end
  result
end

The popular_comments_array method is responsible for fetching all the comments, selecting all comments with more than 40 likes, and collecting the comments in an array of hashes. It is difficult to test all the components of this method individually because the code is all is one method. Let’s split the code up into single purpose methods:

def comments
  Comment.all
end

def popular_comments(comments)
  comments.select { |comment| comment.likes > 40 }
end

def comment_to_hash(comment)
  { title: comment.title, body: comment.body }
end

def popular_comments_array(comments)
  popular_comments(comments).inject([]) do |memo, comment|
    memo.push(comment_to_hash(comment))
    memo
  end
end

This code is procedural so parameters are being passed excessively, but this example demonstrates how much cleaner and more testable single purpose methods are than multi-purpose methods.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s