Rails : Martin Fowler’s Tell Don’t Ask principle in Ruby

As Martin Fowler said

Tell-Don’t-Ask is a principle that helps people remember that object-orientation is about bundling data with the functions that operate on that data. It reminds us that rather than asking an object for data and acting on that data, we should instead tell an object what to do. This encourages to move behavior into an object to go with the data.

Let’s imagine we need to monitor certain values, signaling an alarm should the value rise above a certain limit. If we write this in an “ask” style, we might have a data structure to represent these things…

class AskMonitor
  attr_reader :alarm
  attr_accessor :value, :limit, :name,

  def initialize(name, limit, alarm)
    @name = name
    @limit = limit
    @alarm = alarm


We would then use the data structure like this

alarm = Alarm.new
am = AskMonitor.new("Time Vortex", 2, alarm)
am.value = 3
if am.value > am.limit
  am.alarm.warn("#{am.name} is too high")

“Tell Don’t Ask” principle believes in moving the behavior inside the respective object. Just tell the object to do stuff. Don’t ask.

class TellMonitor
  # Attributes same as AskMonitor
  # but, has new behavior

  def value=(value)
    @value = value

    if @value > limit
      alarm.warn("#{name} too high")

and use of data-structure would be like

tm = TellMonitor.new("Time Vortex Hocus", 2 , alarm)
tm.value = 3





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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s