What is a God object and how to break it?
God objects explained through their warning signs, causes, and a step-by-step refactoring approach using characterization tests, extraction, interfaces, and dependency injection.
What is a God object and how to break it?
Every long-running project has that one class which everybody is afraid of. It is 5000 lines long, it has 80 methods, it knows about the database, the UI, the emails and the business rules, and every new feature somehow ends up in it. We call it as God object, because it knows everything and does everything. In this article, we are going to see what is a God object, how it is born, why it is dangerous and how to break it step by step with a refactoring example.
TL;DR Summary
- God object is a class which knows too much or does too much.
- It is an anti-pattern which violates Single Responsibility Principle.
- It is born slowly, one “small” method at a time.
- It causes merge conflicts, fear of change, slow builds and untestable code.
- Don’t rewrite it in one go, refactor it in small and safe steps.
- Write characterization tests first, then extract classes by responsibility.
- Measure the progress with simple metrics like lines of code and number of dependencies.
Challenges
Every change touches the same file
When most of the logic lives in one class, every developer is editing it for every feature. Merge conflicts are daily problem, and resolving them in a 5000 line file is risky. One wrong merge can break the feature which someone else delivered yesterday.
Fear of change
Nobody fully understands the God object. A change in one method has side effects in another method through shared fields. Developers add new code at the end of the class instead of fixing the existing code, which makes it even bigger.
Impossible to test
The God object creates its own database connections, reads the configuration, sends the emails and writes the files. To test one small calculation, you need the full environment. As a result of this, there are no unit tests, and without tests, nobody dares to refactor. It is a vicious circle.
Knowledge silo
Usually, one or two senior developers know how the God object works. When they are on leave, the issues are waiting, and the MTTR is increasing.
What is a God object?
A God object (also called as God class) is an object that knows too much or does too much, by holding a large share of the application’s data and behaviour in a single class.
In simple terms, it is a class with too many responsibilities. It is the opposite of the Single Responsibility Principle which we discussed in the SOLID Principles - Part 1 article.
Think about a small office where one person is the receptionist, accountant, HR manager and IT support. It works when the office has five people. When the office grows to fifty, that person becomes the bottleneck and everything stops when he is sick.
How a God object is born?
Nobody creates a God object on purpose. It is born due to couple of reasons,
- The first version had only few methods, and “it is easier to add one more here”.
- Deadlines, “we will refactor later” and later never comes.
- Names like
FundManager,Helper,Utility,CommonServicewhich accept anything. - No code review on class size and responsibility.
How to identify a God object?
Here are some signs,
- The class has more than few hundred lines and many unrelated methods.
- It is very hard to describe the class in one sentence without “and”.
- It has many private fields which are used by only few methods each.
- It depends on many other classes (database, file, email, HTTP, configuration).
- It shows up in almost every commit in source control history.
Tools like Visual Studio Code Metrics (Analyze → Calculate Code Metrics) or NDepend help you to find the classes with high lines of code, high class coupling and low maintainability index.
Refactoring by example
Let us take a simplified version of a God object from a fund management application,
public class FundManager
{
public Fund GetFund(int id) { /* SQL query */ }
public void SaveFund(Fund fund) { /* SQL insert/update */ }
public bool ValidateFund(Fund fund) { /* 200 lines of rules */ }
public decimal CalculateNav(Fund fund) { /* NAV calculation */ }
public decimal CalculateFee(Fund fund) { /* fee rules */ }
public byte[] GenerateFactsheetPdf(Fund fund) { /* PDF generation */ }
public void EmailFactsheet(Fund fund, string to) { /* SmtpClient */ }
public void ImportPricesFromCsv(string path) { /* file parsing */ }
public void WriteAuditLog(string message) { /* file logging */ }
// ... 70 more methods
}
Steps to break it:
Follow the following steps to break the God object safely.
-
Write characterization tests first. Before changing anything, write tests which capture the current behaviour, even if the behaviour looks wrong. These tests are our safety net. If the class is not testable at all, start with few integration tests around the public methods.
-
Group the methods by responsibility. List all methods and mark which responsibility each one belongs to. In our example, we can see these groups,
- Data access -
GetFund,SaveFund - Validation -
ValidateFund - Calculation -
CalculateNav,CalculateFee - Factsheet -
GenerateFactsheetPdf,EmailFactsheet - Import -
ImportPricesFromCsv - Logging -
WriteAuditLog
- Data access -
-
Extract one class at a time. Start with the group which has least dependencies on the rest, mostly the calculation logic. Move the methods to a new class and let the old method delegate to it.
public class NavCalculator { public decimal Calculate(Fund fund) { /* moved code */ } } public class FundManager { private readonly NavCalculator _navCalculator = new NavCalculator(); public decimal CalculateNav(Fund fund) { return _navCalculator.Calculate(fund); } }Run the tests after every extraction. The callers don’t know anything has changed.
-
Introduce interfaces and inject the dependencies. Once the classes are extracted, add interfaces (
IFundRepository,IFactsheetGenerator,INavCalculator) and inject them through the constructor. Refer the “How to use Dependency Injection with an IoC container in ASP.NET MVC?” article for detailed information. -
Move the callers to the new classes. Update the controllers and other callers to use the new classes directly instead of
FundManager. Do it one caller at a time. -
Delete the empty shell. When no one is using
FundManageranymore, delete it. It is a good feeling, I promise.
After refactoring, the structure looks like this,
public class FundRepository : IFundRepository { }
public class FundValidator : IFundValidator { }
public class NavCalculator : INavCalculator { }
public class FeeCalculator : IFeeCalculator { }
public class FactsheetGenerator : IFactsheetGenerator { }
public class FactsheetMailer : IFactsheetMailer { }
public class PriceCsvImporter : IPriceImporter { }
Each class is small, has one reason to change and can be tested in isolation.
Note: Don’t stop the feature work for a “big refactoring sprint”. It is very hard to get the business approval and the risk is high. Instead, break the God object gradually, every time a feature touches it, extract one more piece (Boy Scout Rule).
How to prevent it?
- Add a class size and responsibility check in your code review checklist.
- Avoid generic names like
Manager,Helper,Utility,Common. If you can’t find a specific name, the class is probably doing too much. - Track the code metrics (lines of code, class coupling) for the big classes over the period and make it visible to the team.
- Keep the unit test coverage on the core logic, so the refactoring is always safe.
Wrap up
In this article, we have looked at what is a God object, how it is born, how to identify it and how to break it step by step with characterization tests, extraction and dependency injection. I really appreciate that you took the time to read this article. In the next article, I will walk you through how to write unit tests with NUnit and Moq using the AAA pattern.
Related Posts
Why we need Clean Code?
Why clean code matters, what makes code clean (meaningful names, small functions, guard clauses, comments that explain why) and how to bring the practice into your team.
Code review checklist for .NET teams
A practical .NET code review checklist covering design, readability, correctness, errors, security, performance, testing, operations, and constructive review comments and discussion.
How to do TDD (Test-Driven Development)?
Test-Driven Development explained through the Red-Green-Refactor cycle and a step-by-step fund-universe example built with tests first for practical development and design.