Ruby Science
Duplicated Code
One of the first principles we’re taught as developers: Don’t Repeat Yourself.
Symptoms
- You find yourself copying and pasting code from one place to another.
- Shotgun surgery occurs when changes to your application require the same small edits in multiple places.
Example
The QuestionsController
suffers from duplication in the
create
and update
methods.
# app/controllers/questions_controller.rb
def create
@survey = Survey.find(params[:survey_id])
= params.
question_params require(:question).
:title, :options_attributes, :minimum, :maximum)
permit(@question = type.constantize.new(question_params)
@question.survey = @survey
if @question.save
@survey
redirect_to else
:new
render end
end
def update
@question = Question.find(params[:id])
= params.
question_params require(:question).
:title, :options_attributes, :minimum, :maximum)
permit(@question.update(question_params)
if @question.save
@question.survey
redirect_to else
:edit
render end
end
Solutions
- Extract method for duplicated code in the same file.
- Extract class for duplicated code across multiple files.
- Extract partial for duplicated view and template code.
- Replace conditional with polymorphism for duplicated conditional logic.
- Replace
conditional with null object to remove duplicated checks for
nil
values.
Prevention
Following the single responsibility principle will result in small classes that are easier to reuse, reducing the temptation of duplication.
Ruby Science
The canonical reference for writing fantastic Rails applications from authors who have created hundreds.