ruby-style-guide icon indicating copy to clipboard operation
ruby-style-guide copied to clipboard

best practice for long method signatures with many defaults

Open askreet opened this issue 11 years ago • 3 comments

I didn't see this defined in the guide, sorry if I'm just not seeing it.

The guide should define a best practice for long method signatures, like:

def do_something(os = 'precise', os_bits = 64, instance_type = 'instance-store', min_priority = 7)
...
end

For example, here are some options:

def do_something(os = 'precise', os_bits = 64,
                 instance_type = 'instance-store', min_priority = 7)
def do_something(os = 'precise',
                 os_bits = 64,
                 instance_type = 'instance-store',
                 min_priority = 7)
def do_something(
  os = 'precise',
  os_bits = 64,
  instance_type = 'instance-store',
  min_priority = 7)

askreet avatar Feb 20 '14 16:02 askreet

def do_something(
    os = 'precise',
    os_bits = 64,
    instance_type = 'instance-store',
    min_priority = 7)

Rationale: visually distinctive indentation leads the eye upward to the function/method name and, reading downward, makes clear where later statements resume.

Alternately, flag any parameter list over n (default 4?) long as a violation and recommend a parameter hash instead.

jdickey avatar Feb 20 '14 18:02 jdickey

Personally, I think options 1 & 2 most appealing; 3 looks too much like a method call to me.

@jdickey RuboCop already flags methods with more that n args. I don't think that using option hashes is a good idea, since they obscure the signature of the method. Ruby 2.0 keyword args are much better idea for those that don't have to support Ruby 1.9.

bbatsov avatar Feb 21 '14 10:02 bbatsov

I'd prefer option #2 from the OP and next (but like less) the option by jdickey

pwolanin avatar Feb 26 '14 14:02 pwolanin