Return to site

Refactoring tips

inspired by Java Champion Henry Tremblay

· java,mashup

From Refactor together


The goal is to test.

Before refactoring, test.

  1. You add unit test.
  2. Run test coverage.
  3. Add missing code pieces.
  4. Run mutation testing.
  5. Add performance testing.

Do whatever it takes to test.

Change anything you want.

Only use static when you are not planning to mock. Ever.

Code that is hard to test is bad code.

Extraction of hardwritten string into constant.

Use AssertJ.

Really fluid API, and error messages 10 times better than Hamcrest.

Clean after yourself.

When you do a test, you want to leave the JVM in the same state as before which means you should close all the threads you started, you should clear all the system properties you added, you should destroy all the singletons you've triggered to be instantiated. Use @After or @Rule.

If you use PowerMock you are doing something wrong.

PowerMock allows to mock private, final, static methods. Mocking such things could rveal a poor design.

Use automated refactoring until testable.

It should work or explode.

When refactoring, an app completely failing is better than an undebuggable sneaky issue.

Use Inversion of control AKA dependency injection.

Do it everywhere possible, removing singletons.

Avoid complex functional code in tests.

Test code is still code. 

Test code deserves to be refactored.

Group tests by theme.

Do not make humongous tests classes, split in relevant theme as much as you can.

For date use in tests, use Clock class and parse it in your method and do partial mock.

'EasyMock.partialMockBuilder' to mock only one method of an object with 'addMockMethod("myMethod")' then 'andStubReturn()'.

Do not sleep/wait.

No Thread.sleep().

Forget about performance for a second.

Better use tiny methods than fearing it would cost performance to do so. Tiny methods helps spot bottlenecks.

ROI (Return On Investment).

Your refactoring has to bring value.

Try TDD as much as you can.


Refactoring by Martin Fowler.


->Test coverage:

->Mutation testing:


* Gating:

Take away

->Playlist of recommended books:

->Live course on O'Reilly:


->Mocking time:

->Refactoring challenge: