Refactoring

Chuck Greb
Android Testing
Published in
2 min readSep 5, 2018
The old and new Tappan Zee Bridge side by side by Andrew Dallos via Flickr Creative Commons

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” — Martin Fowler (1999)

What is (or isn’t) a refactor

In Working Effectively with Legacy Code, Michael Feathers defines refactoring as “the act of improving design without changing its behavior.”

To me, what is most significant about this definition is what refactoring is not.

Refactoring is not adding a new feature.

Refactoring is not fixing a bug.

Refactoring is not optimization.

Refactoring is making a series of small structural changes to improve readability and maintainability of software without modifying existing behavior.

There have been too many times when I’ve been asked to review a pull request that has a description that starts out with something like the following:

Refactor presenter to handle dialog button click events…

Wrong!

If you are changing the behavior, it’s not a refactor.

But how can we be sure that when making small incremental improvements to the design of our system that we are not unintentionally changing the behavior?

Tests!

Refactoring becomes much easier (and safer) if you have a robust suite of unit tests and instrumentation tests to verify the behavior of your library or app.

Refactoring in Android Studio

Fortunately, Android Studio has a powerful set of built-in refactoring tools powered by the IntelliJ platform.

Android Studio Refactor Menu

The Refactor menu in Android Studio will automate many common refactoring tasks including:

  • Rename class/method/variable
  • Change a method signature
  • Move a class to a new package
  • Extract a method or variable
  • Extract a method parameter
  • Create a new constant
  • Inline a method
  • Safe delete
  • And more…

For more information about how to execute each of these automated refactors, checkout this excellent article by Jeroen Mols.

Refactoring can be a useful tool for making incremental improvements to Android legacy code. In the next post, we’ll explore how we can begin to add tests before refactoring where none currently exist.

This post is part of a series on working with legacy code on Android. It explores ways we can navigate, maintain, improve, and evolve legacy code using clean architecture, refactoring, dependency breaking techniques, and testing.

If you found this article helpful, please give it some applause 👏 to help others find it. You can also leave a comment below. Thanks!

--

--

Chuck Greb
Android Testing

Mission-driven engineering leader. Community organizer. Digital minimalist.