DEV Community

Burdette Lamar
Burdette Lamar

Posted on

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?

Top comments (3)

Collapse
 
dbanty profile image
Dylan Anthony

Oh yeah, stacking is great! I added it to my companies style guide for Python :). An useful tip to point out, use trailing commas! This way your Git diffs only highlight the lines you actually changed.

a_list = [
    'Item1',
    'Item2',
]

big_string = (
    'A very long sentence'
    ' can be put on multiple lines.'
)
Collapse
 
burdettelamar profile image
Burdette Lamar

Thanks, Dylan.

But be careful not to put a comma on the last line of a stack of attr_accessor method names. Causes major problems for the code that follows.

Collapse
 
dbanty profile image
Dylan Anthony

I’ll keep that in mind if I ever write in Ruby. It keeps floating around my list of languages to try but it seems to solve mostly the same problems as Python so I haven’t found a good reason to play with it yet.