Ruby Science
Introduce Parameter Object
This is a technique to reduce the number of input parameters to a method.
To introduce a Parameter Object:
- Pick a name for the object that represents the grouped parameters.
- Replace the method’s grouped parameters with the object.
Uses
- Removes long parameter lists.
- Groups parameters that naturally fit together.
- Encapsulates behavior between related parameters.
Example
Let’s take a look at the example from Long Parameter List and improve it by grouping the related parameters into an object:
# 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
# app/views/mailer/completion_notification.html.erb<%= @first_name %> <%= @last_name %>
By introducing the new parameter object recipient
we can
naturally group the attributes first_name
,
last_name
, and email
together.
` app/models/recipient.rb
# app/mailers/mailer.rb
class Mailer < ActionMailer::Base
from: "from@example.com"
default
def completion_notification(recipient)
@recipient = recipient
mail(to: recipient.email,
subject: 'Thank you for completing the survey'
)end
end
Notice that we’ve also created a new full_name
method on
the recipient
object to encapsulate behavior between the
first_name
and last_name
.
# app/views/mailer/completion_notification.html.erb<%= @recipient.full_name %>
Next Steps
- Check to see if the same data clump exists elsewhere in the application and reuse the parameter object to group them together.
- Verify the methods using the parameter object don’t have feature envy.
Ruby Science
The canonical reference for writing fantastic Rails applications from authors who have created hundreds.