---
title: "Tech Tip #34: Write the tests before you refactor"
description: "Never optimise code you can't test."
url: https://greencode.ai/tech-tips/34-tests-before-you-refactor/
---

# Tech Tip #34: Write the tests before you refactor

**Never optimise code you can't test.**

[Watch the video](https://media.greencode.ai/shorts/tests-before-you-refactor-577830528b1a.mp4)

Video created by [explainapaper.com](https://explainapaper.com/?utm_source=greencode.ai&utm_medium=film&utm_campaign=made-by)

### 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](https://greencode-constitution.org/?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode) (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](https://docs.sonarsource.com/sonarqube-server/?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode): 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](https://greencode.ai/benefit/reduced-software-issues/).

### Tags

#testing#refactoring#legacy

### Sources

- [GreenCode Constitution (Kapenekakis et al., GreenAI workshop, ECML PKDD 2026): meta-principle 1, correctness above all, and 3, preserve public interfaces](https://greencode.ai/publications/greencode-constitution-agent-principles-for-optimizing-code-and-llm-inference-en/)
- [GreenCode Constitution skill, energy anti-patterns: M1 never alter observable behaviour or break tests for energy gains](https://greencode-constitution.org/skill.md?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode)
- [W3C, Web Sustainability Guidelines: automated test suite covering critical functionality](https://www.w3.org/TR/web-sustainability-guidelines/#automated-tests)

[All GreenCode Tech Tips](https://greencode.ai/tech-tips/)

#### Key Facts

- Tip **#34**
- For **Developers**
- Category **Testing, CI and code quality**
- Format **short video**
![GreenCode](https://greencode.ai/wp-content/uploads/2024/12/greencode-logo-website-small-colours-2.webp)

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

[Get in touch](https://greencode.ai/contact/)
