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[])
  question_params = params.
    require().
    permit(, , , )
  @question = type.constantize.new(question_params)
  @question.survey = @survey

  if @question.save
    redirect_to @survey
  else
    render 
  end
end

def update
  @question = Question.find(params[])
  question_params = params.
    require().
    permit(, , , )
  @question.update(question_params)

  if @question.save
    redirect_to @question.survey
  else
    render 
  end
end

Solutions

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.

Work with us to make a new Rails app, or to maintain, improve, or scale your existing app.