A guide for refactoring code Last updated on May 5, 2019

Refactoring

A guide for refactoring code

Contents


Initial Review

Here are some questions to think about when looking at and reviewing code.

  • What is the design and structure of the code like?
  • Any repeated code that could be refactored?
  • What are the sizes of methods, modules and classes?
  • How is information passed between objects and methods?
  • What dependencies are there?
  • Is is clear where dependencies come from?
  • Are there any conventions, such as Ruby on Rails design conventions, that could be put into practice more?
  • Do methods and class names describe what they do?

Design Principles

  • Don’t Repeat Yourself - Avoid repeating code, for example using methods and classes, such as Service Objects
  • Inheritance - Base class that child classes share code with
  • Composition - Write code in modules that can be included in other
  • Single Responsibility Principle - Aim for a class or module to be responsible for one purpose
  • Dependency Injection - Dependent code can be added and replaced easily without breaking functionality, for example pass in dependencies as arguments when creating a new instance of a class
  • Separation of Concerns - Ensuring code is modular and uses an interface to interact with other parts of a larger system

Also see the Ruby on Rails conventions and design principles

Design Patterns

Here are a few design patterns, outside of the ones built into Ruby on Rails (such as Concerns).

  • Service Objects - Carry out an action an do not hold state. Normally have one public method, such as “call” or “perform”.
  • Presenter - Create an interface to present model records in views
  • Decorator - Add some functionality to another object

Code Extractions

Extractions could be useful when code is repeated, too long, or complex.

  • public methods
  • private methods
  • separate class
  • module that is included as a mixin
  • a set of classes grouped in a namespace
  • a library or gem

Think about design principles and design patterns when extracting code for refactoring in order to ensure long-term maintainability and ease or reading the code by others.

Coding Conventions