Tech Tip #34: Write the tests before you refactor

Never optimise code you can't test.

Video created by explainapaper.com

The problem

An energy fix that changes behaviour is a bug. Legacy code often has no tests, so an optimisation cannot be checked and nobody dares merge it.

The fix you can use today

  • Pin current behaviour with characterisation tests before changing anything.
  • Run the full suite before and after every optimisation.
  • Keep public interfaces unchanged unless you mean to change them.

GreenCode researchers put one rule first: never break the code to save energy.

Tools that help

  • GreenCode Constitution skill (GreenCode researchers): open-source energy principles and a catalogue of 37 energy anti-patterns that an AI coding agent can follow to find and fix waste like this
  • SonarQube: static analysis for code smells, bugs and security issues, with quality gates in CI

How GreenCode helps

GreenCode helps tackle this by generating the missing unit tests before it changes any code. Every optimisation is then gated on quality issues, security flaws and error rate, which must not rise. More on this.

Tags

#testing#refactoring#legacy

Sources

Transcript

Never optimise code you cannot test. An energy fix that changes what the code does is a bug. And a lot of old code has no tests at all. So nobody can check the optimisation. And nobody dares to merge it. A saving bought with a broken feature costs far more than it saves. Here is the fix you can use today. Before you change anything, write tests that pin down what the code does now. Run the full test suite before and after every optimisation. Keep public interfaces the same, unless you mean to change them. GreenCode researchers put one rule first: never break the code to save energy. GreenCode's Constitution skill can guide an AI coding agent to fix waste safely. Then catch new bugs and security issues, using tools like SonarQube. GreenCode helps tackle this by writing the missing unit tests before it changes code. Then no change may raise quality issues, security flaws or errors. That was GreenCode Tech Tip number thirty-four. Follow for the next tip, and find more on greencode.ai/tech-tips.

All GreenCode Tech Tips · All GreenCode videos

  • Tip #34
  • For Developers
  • Length 1:08
  • Category Testing, CI and code quality
GreenCode

Want this checked on your own system? Talk to the GreenCode team.

Get in touch