Refactoring

Controllable process
improving your code
without writing new
functionality.

What is Refactoring?

Refactoring is the controllable process of systematically improving your code without writing new functionality.

The goal of refactoring is to pay off technical debt.

Refactoring results in clean code and simple design.

Clean code = Simple code

  • Clean code passes all tests.
  • Clean code is obvious for other programmers.
  • Clean code does not contain duplication.
  • Clean code contains a minimum number of classes and other moving parts.

Clean code is easier and cheaper to maintain.

How is refactoring done?

Refactoring is best performed as a series of minor changes. Each change improves the existing code slightly while keeping it in functional condition.

Three key components of correct refactoring:

  1. No new functionality is created during refactoring.
  2. All existing tests should be successfully passed after refactoring.
  3. The code becomes simpler after refactoring.

When is refactoring needed?

Rule of Three

  1. When you do something for the first time, you are just doing it to get done.
  2. When you do something similar for the second time, you cringe at having to repeat but do the same thing anyway.
  3. When you do something for the third time, you start refactoring.

When adding a feature

  1. Refactoring helps to understand other people's code. If it becomes necessary to add a feature to unclear code, refactoring it makes things obvious for you and those coming after you.
  2. Refactoring makes it easier to add features. New features are added more smoothly and with less effort.

When fixing a bug

Bugs resemble cockroaches: they love to live in the darkest, mustiest places of your code. Clean up your code and the errors will practically find themselves.

Managers appreciate proactive refactoring, since it eliminates the need to create special refactoring tasks later. Happy bosses mean happy programmers!

During code review

Review may be your last chance to tidy up your code before it becomes available to the public.

The best way to review is together with the author of the code. You propose changes and decide, together with the author, how difficult it will be to implement various refactoring techniques. Small changes can be made right on the spot.