What is a God object in c# ?

A God object contains cluttered code that is difficult to maintain, extend, use, test, and integrate with other parts of the application. God objects violate the single responsibility principle and the Law of Demeter. 

The Law of Demeter, or principle of least knowledge, reduces dependencies between classes and helps build components that are loosely coupled.

Here is a list of the characteristics of a God object:
  • Too many functions in a class
  • Knows too much about the application and can interact with all the data
  • Difficult to maintain over time because changes to the class of the God object typically introduce problems or side effects
  • Extremely complicated since it maintains the state of most of the application
God object example in C#
The solution to the God object anti-pattern is to split related functionality into smaller and more manageable classes — i.e., to design classes that have strong cohesion and are loosely coupled with one another.

Let’s dig into some code to understand the God object anti-pattern better. Let’s say you are building a recruitment management system. Create the following class in the Program.cs file.
public class Candidate
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public DateTime InterviewDate { get; set; }
        public int RecruiterId { get; set; }
        public string Recruiter { get; set; }
        public int InterviewerId { get; set; }
        public string Interviewer { get; set; }
        public string InterviewerRemarks { get; set; }
        public decimal CurrentSalary { get; set; }
        public decimal ExpectedSalary { get; set; }
    }
The Candidate class shown here contains several properties that shouldn’t be part of it. In essence, this class is doing too many things, and thus violates the single responsibility principle. This is a good example of a God object. In other words, an instance of the Candidate class is a God object because it contains too much information.

Post a Comment

0 Comments