How do you refactor a God class?

Oliver Watkins picture Oliver Watkins · Feb 14, 2013 · Viewed 17.6k times · Source

Does anyone know the best way to refactor a God-object?

Its not as simple as breaking it into a number of smaller classes, because there is a high method coupling. If I pull out one method, i usually end up pulling every other method out.

Answer

Fabian Schmengler picture Fabian Schmengler · Feb 14, 2013

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