Skip to main content

God Object

Description

What does it look like?

  • A single class or module holds too many responsibilities
  • All kinds of processing are crammed into the class, causing changes or extensions to have wide-reaching impact
  • Data storage, business logic, and state management are all mixed together

Why is it a problem?

  • The class loses its clear purpose, resulting in unreadable and fragile code
  • Difficult to test due to numerous dependencies and assumptions
  • Cannot be reused or separated—a breeding ground for spaghetti code

Bad Example of the Anti-pattern

// Godクラス:責務が全部入り
class OrderManager {
private orders: string[] = [];
private userEmail: string = "";
private discountType: string = "none";

setUser(email: string) {
this.userEmail = email;
}

addOrder(productId: string) {
this.orders.push(productId);
}

applyDiscount(type: string) {
this.discountType = type;
}

calculateTotal(): number {
let basePrice = this.orders.length * 1000;
if (this.discountType === "student") {
return basePrice * 0.8;
} else if (this.discountType === "member") {
return basePrice * 0.9;
}
return basePrice;
}

confirmOrder() {
// 1. 在庫調整
console.log("在庫を減らす");

// 2. メール通知
console.log(`メールを ${this.userEmail} に送信`);

// 3. ログ出力
console.log("注文完了ログ");
}
}

Issues

  • Order data handling, discount logic, notification, and logging are all handled by a single class
  • It is unclear “what this class is supposed to do”
  • The class tends to grow into a monolith that is difficult to test and prone to cascading changes

Refactoring by Pattern

Design patterns that can address this

PatternOverviewMain Refactoring Approach
FacadeHide internal complexity behind a unified interfaceMake multiple subsystems accessible through one API
StrategyMake behavior interchangeableImprove testability and extensibility
StateSeparate behavior by internal stateReplace conditionals with state-specific classes
CompositeOrganize in a tree structure for unified accessClarify responsibilities across hierarchy
IteratorAbstract the way collections are traversedEncapsulate iteration logic for better maintainability