Josh Hepworth

Using Variables to Communicate Intent
Communicating With Code

Achieving a high level of clarity in your code is difficult. English already allows for a tremendous amount of interpretation, and engineers often twist the language in ways that don't always help limit the possibilities.

One technique I've found useful to provide future me with context is naming the results of intermediate steps in a method rather than chaining or nesting calls. This gives me the chance to provide a description for an object that often ends up being extremely useful when returning later to debug or update that part of the application.

Here's a very, very simple example that is almost certainly overkill. However, the simplicity helps highlight the structure. The method begins with the variable definitions that serve as a way to communicate what information this method needs and what other properties the method collaborates with.

class Book

  # ...

  def description
    publisher_text = publisher.name
    published_year = published_at.year

    "#{title} ©#{published_year} #{publisher_text}"
  end

  # ...

end

As things get more complex, this pattern can help define attributes of collections of objects or a properties of a single object that are useful to know as you read the rest of a method.

class BulkOrderProcessor

  # ...

  def process!
    cancelation_window = 1.day
    processable_orders = Order.where("completed_at < ?", Time.zone.now - cancelation_window)

    processable_orders.map(&:process!)
  end

  # ...

end

In the above, slightly more complex example, I use variables to make the purpose of 1.day explicitly clear, and I also ensure it's clear what property of the orders I'm concerned about with the processable_orders variable.

This style of code doesn't always replace the need for documentation or inline comments about the code, but it makes the resulting method implementations easier to understand. It allows me to think more about what the action taking place rather that what object is being acted upon.