Ruby idioms : Avoid check class membership

Avoid use class, is_a? and kind_of? to check class membership. Replace these statement with a message to the object that respond to the message. The code below is an anti-pattern.

if mortgage.class==FixRateMortgage
   mortgage.change_rate_not_allowed
else
   mortgage.rate=rate
end

The code below is more idiomatic in Ruby.

class Mortgage
  attr_accessor :rate
end 

class FixedRateMortgage < Mortgage
  def initialize()
    @rate=5
  end
  def rate=(rate)
    change_rate_not_allowed
  end

  def change_rate_not_allowed
     puts "The rate in a fixed rate mortage can not be change"
  end
end

Sending the method rate= to either kind of classes will result in the appropriate behaviour.

About these ads

2 comments so far

  1. arjunghosh on

    Liked this concept…nice

  2. roundabout on

    This isn’t really a ruby issue, but more of a general OO issue. An object should handle tasks regarding itself internally, rather than trusting others to do it properly.


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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: