God Class: Breaking Single Responsibility Principle

          “God object: In object-oriented programming, is an object that knows too much or                  does too much.” 

– Source: Wikipedia

God class in OOP doesn’t stand for a good thing; here it’s called an anti-pattern. In Object Oriented Programming, we create a new class to define the properties and capabilities of an object. It is using these objects that we build our system, mimicking how it would work in the real world.

For example: Let’s assume that we are trying to build a software to manage the office of a school.

In a typical school office, there would be different departments to handle different parts of the administration. For example, the Purchase department for the purchases, the Accounts department for the accounts, the Records department for the records, the HR department to manage the staff. When one department wants something from another department, it would ask that department for the information. As per protocol, it shouldn’t take the files from the other department without the staff or the department lending it.

So, mimicking the real world would mean that we build one class for each department of the office. We should build a class called Accounting, and in that class we will write all the functions that the Accounts department does, and only what it does. We will not write the functions for the HR department in the account class. Keeping all the code for a particular function at a single place makes our code more efficient and cleaner. Now every time we want the Accounts department to do something, we will create an object of that class and pass the data we have to get the information we need. Note: In an actual software we will further break down the Accounts department to even smaller classes, so that it would be even more simpler to handle.    In limiting the Accounts department to handle only a single responsibility, we know where exactly to look when something related to accounting is found to be broken. But as our software grow, we unknowingly or knowingly give a class more than one responsibility. Doing so might seem to be efficient when you write it – but when we make changes to one functionality of a class, we risk breaking the second functionality of that class. We have introduced an uncertainty into our system. Following the Single Responsibility Principle as much as possible ensures that your code is more maintainable, readable and changeable. And most importantly, we can be sure that changing the codes in a particular class would only break that single functionality.]]>