Tell don’t ask

This is a “rule of thumb” to improve abstractions while coding. Instead of asking to another domain what is their state to execute something, you just say “please, execute this when it makes sense to do so”

Avoid:

def complete_invoice
  invoice.due_date = Date.today
  ...
  if invoice.ready_to_be_sent?
    InvoiceSender.send(invoice)
  end
end

Better:

def complete_invoice
  invoice.due_date = Date.today
  InvoiceSender.send_ready_invoice(invoice)
end
 
class InvoiceSender
  def send_ready_invoice(invoice)
      return unless invoice.ready_to_be_sent?
      InvoiceSender.send(invoice)
  end
end
 

We could abstract it even further, and trigger the InvoiceSender at any moment to send invoices that are ready.

Why?

I believe it helps keeping the code easier to follow and to ready, each if breaks the flow and makes you stop and think about that, it’s not like reading a book. And if there are complex conditions, it becomes even harder. When you ‘tell don’t ask”, you can read your code closer to the way you read a book. Your method is telling a story.

This is part of Tips for Software Engineers