How do you refactor a God class?

I assume "God Object" means a huge class (measured in lines of code).

The basic idea is to extract parts of its functions into other classes.

In order to find those you can look for

  • fields/parameters that often get used together. They might move together into a new class

  • methods (or parts of methods) that use only a small subset of the fields in the class, the might move into a class containing just those field.

  • primitive types (int, String, boolean). They often are really value objects before their coming out. Once they are value object, they often attract methods.

  • look at the usage of the god object. Are there different methods used by different clients? Those might go in separate interfaces. Those intefaces might in turn have separate implementations.

For actually doing these changes you should have some infrastructure and tools at your command:

  • Tests: Have a (possibly generated) exhaustive set of tests ready that you can run often. Be extremely careful with changes you do without tests. I do those, but limit them to things like extract method, which I can do completely with a single IDE action.

  • Version Control: You want to have a version control that allows you to commit every 2 minutes, without really slowing you down. SVN doesn't really work. Git does.

  • Mikado Method: The idea of the Mikado Method is to try a change. If it works great. If not take note what is breaking, add them as dependency to the change you started with. Rollback you changes. In the resulting graph, repeat the process with a node that has no dependencies yet. http://mikadomethod.wordpress.com/book/


It's like Jenga. You will need patience and a steady hand, otherwise you have to recreate everything from scratch. Which is not bad, per se - sometimes one needs to throw away code.

Other advice:

  • Think before pulling out methods: on what data does this method operate? What responsibility does it have?
  • Try to maintain the interface of the god class at first and delegate calls to the new extracted classes. In the end the god class should be a pure facade without own logic. Then you can keep it for convenience or throw it away and start to use the new classes only
  • Unit Tests help: write tests for each method before extracting it to assure you don't break functionality