The God object is a part of the code smell group and it is a kind of object that knows too much or does too much. That means a huge class in terms of number of lines of code. It is very famous in bad programming because it creates tight coupling and increases the challenges in the code maintainability. If a class contains too many functions or properties, then it increases the lines of codes in that class and this class will suffer from God Object, a bad programming practice. It is a kind of an Anti-Pattern because it opposes a common design principle.
Two famous SOLID principles are "Single Responsibility" and "Interface Segregation." The main objective of these two principles is to separate the large solution into small pieces of logical code blocks with interfaces and classes. But, the God Object doesn't care about these principles. So, it enters into the category of anti-design pattern.
Below is an example of a class that is a God Object.- using System;
- namespace DelegateExample {
- public class EmployeeUtils {
- public void FetchEmployeeDetails(string employeeId) {}
- public void SaveEmployeeDetails(EmployeeModel employeeDetails) {}
- public void ValidateEmployeeDetails(EmployeeModel employeeDetails) {}
- public void ExportEmpDetailsToCSV(EmployeeModel employeDetails) {}
- public void ImportEmpDetailsForDb(EmployeeModel employeeDetails) {}
- private class EmployeeModel {
- public string EmployeeId {
- get;
- set;
- }
- public string EmployeeName {
- get;
- set;
- }
- public string EmpplyeeAddress {
- get;
- set;
- }
- public string EmployeeDesignation {
- get;
- set;
- }
- public double EmployeeSalary {
- get;
- set;
- }
- }
- }
- }
The EmployeeUtils class above contains three major design smells.
- Violation of Single Responsibility Principle
This class is doing everything. The functionalities of class should be separated into other different classes and interfaces based on similar type of responsibilities. It will remove the issue of tight coupling and will be easy for maintainability.
- Opposing Design Pattern
It is not following any design pattern principle. Code can't be reused. It is prone to copy-paste for the same.
- Missing Abstraction
This class is missing an abstraction, so writing unit tests will be very difficult. It will expose all members of class.
Solution of the above God Object class
It should follow the SOLID Principle. Interface segregation will be a very good solution for this class.
Create separate Model class for the "EmployeeDetails" like below.
Muhammad IlyasPosted Mar 7, 2018, 4:04 AM
Good example of God Class