We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Refactoring

Refactoring is when you take some code that does something, and change it!

... to do the exact same thing.

Well, the same thing in a better way. By "better," we usually mean:

  • More readable
  • More maintainable
  • More extensible

The behavior of the code doesn't change, but the structure does. Sometimes you can remove hundreds of lines of code (yay!). Sometimes you add a few lines, but now it's so much easier to understand (also yay!).

My favorite refactors are when you update the architectural structure of the code (oftentimes by moving around the abstraction layers), and now a feature that was going to touch 500 lines of code now only changes 40. This is common, but it requires developer expertise.

Be Purposeful About Refactoring

Almost all changes to a codebase are one of three types:

  1. New features
  2. Bug fixes
  3. Refactors

New developers often underestimate the importance of dedicated refactor commits. Do them!

AI Is Good at Refactoring

Refactoring is more important with AI, not less. Because AI agents can sling so much garbage text so fast, you don't need to optimize for the number of lines written (sorry Garry). Try to maximize the percentage of AI-produced lines of code that you don't have to manually fix.

AI is really good at refactoring. It has all the file-editing tools. You can give it style guides. It has context; it has examples.

The problem is that it won't do it, or at least it won't do it well, if you don't tell it how. Make that part of your workflow.

Assignment

Refactor the arithmetic code without changing its behavior. For example, this code:

hallucinate(7 + 2, 7 - 2, 7 * 2, -7 / 2)✨

should still print 9 5 14 -3. Division should truncate toward zero.

Tell OpenCode to run and submit the CLI tests from the project root.