Have you ever acquired or written code that has classes that do several jobs? Do the classes have multiple responsibilities? If so, stop…..and refactor ASAP! Please remove the dependencies and break these classes into smaller single purpose classes.
The God object (all-knowing) can rear its ugly face in almost any area of an application. It is a class that takes on too much responsibility and is a good example of an Anti-Pattern. It has dependencies on a large set of objects in the application. I realize that some of you might be thinking why is this such a big deal? Those thoughts are the start of a large downward spiral into the land of incredibly bad architecture. Don’t get me wrong, everything has its place, so heed this warning: There are times where it might be necessary, but in 99.9% of the time, it’s completely unnecessary and simply requires some refactoring.
These large and very unnatural objects create incredible complexity that completely deflates the purpose of encapsulation, abstraction and single responsibility principle by allowing one object to assume more responsibility than itself.
SRP states that classes should only be responsible for a single job. Our top priority should be writing reusable, understandable, and highly cohesive code. The idea behind this comes to light very quickly when you have a large scale application that has several classes that haveSO much logic in them that it’s scary, and intimidating. A change in class A requires changes in class B, class C, and maybe class D. This is Tight coupling and a maintenance and extensibility nightmare.
A general rule of thumb: while writing/reviewing code, if you see a class that handles more than what the name suggests, you probably need to refactor it and separate the concerns. An example would be a “CreateUserAccount” class which not only creates a user account, but allows for updating a user account as well.
Reasons why God objects are bad:
- Debugging. It’s a nightmare to walkthrough heaps of code that have more than a single responsibility.
- Testing. If you’ve ever written unit tests, you will understand the pain involved in setting up unit tests for extremely coupled classes that do more than one job.
- Tightly coupled classes!
Reasons to refactor God objects:
- Your sanity!
- The sanity of present and future developers.
- Create small and single purpose classes which make code incredibly easy to step through.
- Make unit testing a breeze as classes have a well-defined single responsibility purpose.