Ruby Science
Long Parameter List
Ruby supports positional method arguments which can lead to Long Parameter Lists.
Symptoms
- You can’t easily change the method’s arguments.
- The method has three or more arguments.
- The method is complex due to number of collaborating parameters.
- The method requires large amounts of setup during isolated testing.
Example
Look at this mailer for an example of long parameter list.
# app/mailers/mailer.rb
class Mailer < ActionMailer::Base
from: "from@example.com"
default
def completion_notification(first_name, last_name, email)
@first_name = first_name
@last_name = last_name
mail(to: email,
subject: 'Thank you for completing the survey'
)end
end
Solutions
Introduce parameter object and pass it in as an object of naturally grouped attributes.
Extract class if the method is complex due to the number of collaborators.
Anti-Solution
A common technique used to mask a long parameter list is grouping parameters using a hash of named parameters; this will replace connascence of position with connascence of name (a good first step). However, it will not reduce the number of collaborators in the method.
Ruby Science
The canonical reference for writing fantastic Rails applications from authors who have created hundreds.