Readable Code: Stacking Tokens

burdettelamar

Burdette Lamar

Posted on May 18, 2019

Readable Code: Stacking Tokens

If a collection of tokens serves as a list, consider making it look like a list.

As an example I'll use Ruby's class method attr_accessor, which accepts any number of arguments.

Unstacked:

  attr_accessor :arity, :name, :original_name, :owner, :parameters, :receiver, :source_location, :super_method
Enter fullscreen mode Exit fullscreen mode

Stacked:

  attr_accessor \
    :arity,
    :name,
    :original_name,
    :owner,
    :parameters,
    :receiver,
    :source_location,
    :super_method
Enter fullscreen mode Exit fullscreen mode

Much more readable, no?

Note: For a user-defined method that accept many arguments, stacking may not be the best option. Consider instead whether such a method should accept an object.

Nevertheless:

  def initialize(
    name:,
    address:,
    phone:,
    date_of_birth:,
    debit_card_number:,
    debit_card_pin:,
  )
  end
Enter fullscreen mode Exit fullscreen mode

Another stack-worthy notation:

  %w/
    apple
    banana
    orange
    peach
    persimmon
    pineapple
    scuppernong
    tomato
  /
Enter fullscreen mode Exit fullscreen mode

And of course pretty much everyone already does this:

  {
      :cabbages => 0,
      :cucumbers => 2,
      :peas => 200,
      :potatoes => 4,
      :radishes => 8,
      :sweet_potatoes => 0,
  }

Enter fullscreen mode Exit fullscreen mode

Others? In Ruby? Or in another language?

πŸ’– πŸ’ͺ πŸ™… 🚩
burdettelamar
Burdette Lamar

Posted on May 18, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Code readability metrics?
codereadability Code readability metrics?

February 28, 2020

Readable Code: Stacking Tokens
readability Readable Code: Stacking Tokens

May 18, 2019