markOnSoftware

Tell, Don't Ask

May 29, 2017

Rubyists often write a block of code that is similar to the one below.

account = Account.new
account.balance = 5_000

if account.balance > 2_000
  account.buy_television!
end

This is a code smell. Here’s a better way to do it.

account = Account.new
account.buy_television!

The above example is more direct. It doesn’t ask. It tells object what to do.

Another bad example.

cards = get_credit_cards_for(customer)

if cards.all?(&:active)
  PurchaseOrder.create(customer)
end

The better version.

class PurchaseOrder
  def self.create(customer)
    create_transaction if customer.all_cards_active?
  end
end

PurchaseOrder.create(customer)

In OOP, we want to tell objects what needs to be done, not ask them first.


Mark Chavez

Hi, I'm Mark Chavez. Creator of Get Things Done, yamda, public_apis, js_issues, bitcoin_index and a whole bunch of open-source projects. Join me on my adventures as I unfold the good and bad bits about software writing. You can also follow me on twitter and github for more goodies. Also, I love #oss!