Patterncore
Large Class
Also called god class, blob.
A code smell: a class has too many fields, too many methods or too much code, because it does several jobs, and each change to one job must be made among the parts of the others.
- Family
- code-smell
- Intent
- Find the groups of fields and methods inside a large class that belong together, and give each group a class of its own.
Intent
Find the class that does several jobs at once. Look inside it for groups of fields and methods that are used together and apart from the rest, and move each group into a class of its own. The large class then becomes a small one that uses the others, or it goes away.
Problem
A class is a unit of thought. A reader opens it to learn one idea: what an order is, how a cart works. When one class holds the order, the cart, the shipping address and the tax rules, the reader must learn all of them to change any of them.
Refactoring describes the smell as a class that tries to do too much, which often shows itself as too many fields. It notes that duplicated code is close behind, because a class with many fields tends to repeat the code that uses them.1 The extreme form has its own name. Wikipedia describes a god object as "an object that references a large number of distinct types, has too many unrelated or uncategorized methods, or some combination of both", and adds that "Changes made to the object for the benefit of one routine can have a ripple effect on other unrelated functions."2
The forces are these:
- A class grows one feature at a time. Each feature is small, and the class is the place where the data already is.
- Fields with a common prefix or suffix, such as
shipStreet,shipCityandshipCountry, are a sign of a class that is waiting to be extracted. Refactoring names this sign.1 - A large class is a source of Divergent Change: it changes for many reasons, and the changes for one reason touch code that is there for another.
- Not every field is used by every method. A class whose methods use disjoint sets of fields is several classes in one file.
Solution
Refactoring gives the moves.1 The catalogue at refactoring.com has a card for each refactoring, and gives Extract Subclass as another name for Replace Type Code with Subclasses.3
- Group the fields: Extract Class. Fields that go together, and the methods that use them, move into a class of their own.
- Group by kind: Extract Superclass or Replace Type Code with Subclasses, when some fields and methods belong only to some kinds of object.
- Remove the repeats: a class with too much code often has the same steps in several methods. Extract Function on the shared steps makes the class smaller before any split.
Refactoring also suggests a way to find the groups: look at how the clients use the class. Different clients often use different subsets of the methods, and each subset is a candidate for a class.1 The first edition gives the same moves, and adds Extract Interface for the case where the split is only in what the clients see.4
Example
A checkout class holds the items of a cart, a coupon, and the fields of a shipping address, all with prefixes. The methods for the cart use only the cart fields, and the methods for the address use only the address fields.
import assert from "node:assert/strict";
// Before: one class, two jobs, and fields with prefixes.
class CheckoutBefore {
constructor() {
this.cartItems = [];
this.cartCoupon = null;
this.shipName = "";
this.shipStreet = "";
this.shipCity = "";
this.shipCountry = "";
}
addItem(name, cents) { this.cartItems.push({ name, cents }); }
applyCoupon(percent) { this.cartCoupon = percent; }
cartTotal() {
const sum = this.cartItems.reduce((t, i) => t + i.cents, 0);
return this.cartCoupon === null ? sum : sum - Math.round((sum * this.cartCoupon) / 100);
}
setAddress(name, street, city, country) {
Object.assign(this, { shipName: name, shipStreet: street, shipCity: city, shipCountry: country });
}
shippingLabel() { return [this.shipName, this.shipStreet, `${this.shipCity}, ${this.shipCountry}`].join("\n"); }
isDomestic() { return this.shipCountry === "NL"; }
}
// After: each group of fields has a class, and the checkout uses both.
class Cart {
#items = [];
#coupon = null;
add(name, cents) { this.#items.push({ name, cents }); }
applyCoupon(percent) { this.#coupon = percent; }
get total() {
const sum = this.#items.reduce((t, i) => t + i.cents, 0);
return this.#coupon === null ? sum : sum - Math.round((sum * this.#coupon) / 100);
}
}
class Address {
constructor(name, street, city, country) { Object.assign(this, { name, street, city, country }); }
get label() { return [this.name, this.street, `${this.city}, ${this.country}`].join("\n"); }
isIn(country) { return this.country === country; }
}
class Checkout {
constructor(cart, address) { this.cart = cart; this.address = address; }
isDomestic() { return this.address.isIn("NL"); }
}
const before = new CheckoutBefore();
before.addItem("lamp", 3999);
before.addItem("bulb", 499);
before.applyCoupon(10);
before.setAddress("Ada", "Keizersgracht 1", "Amsterdam", "NL");
const cart = new Cart();
cart.add("lamp", 3999);
cart.add("bulb", 499);
cart.applyCoupon(10);
const after = new Checkout(cart, new Address("Ada", "Keizersgracht 1", "Amsterdam", "NL"));
assert.equal(after.cart.total, before.cartTotal());
assert.equal(after.cart.total, 4048);
assert.equal(after.address.label, before.shippingLabel());
assert.equal(after.isDomestic(), before.isDomestic());
console.log("checkout: tests pass");
checkout: tests pass
In the second version the prefixes are gone, because each prefix became a class name. Cart can be tested with no address, and Address can be used by an invoice or a user profile that has no cart. The checkout keeps only the rule that needs both.
| Language | What the example shows |
|---|---|
| JavaScript | a cart class and an address class extracted, as above |
| Python | the same split, with a dataclass for the address |
| Java | the same split, with a record for the address |
| Go | the same split, with a struct for each part |
from dataclasses import dataclass
# Before: one class, two jobs, and fields with prefixes.
class CheckoutBefore:
def __init__(self):
self.cart_items = []
self.cart_coupon = None
self.ship_name = self.ship_street = self.ship_city = self.ship_country = ""
def add_item(self, name, cents):
self.cart_items.append((name, cents))
def apply_coupon(self, percent):
self.cart_coupon = percent
def cart_total(self):
s = sum(c for _, c in self.cart_items)
return s if self.cart_coupon is None else s - round(s * self.cart_coupon / 100)
def set_address(self, name, street, city, country):
self.ship_name, self.ship_street, self.ship_city, self.ship_country = name, street, city, country
def shipping_label(self):
return "\n".join([self.ship_name, self.ship_street, f"{self.ship_city}, {self.ship_country}"])
def is_domestic(self):
return self.ship_country == "NL"
# After: each group of fields has a class, and the checkout uses both.
class Cart:
def __init__(self):
self._items = []
self._coupon = None
def add(self, name, cents):
self._items.append((name, cents))
def apply_coupon(self, percent):
self._coupon = percent
@property
def total(self):
s = sum(c for _, c in self._items)
return s if self._coupon is None else s - round(s * self._coupon / 100)
@dataclass(frozen=True)
class Address:
name: str
street: str
city: str
country: str
@property
def label(self):
return "\n".join([self.name, self.street, f"{self.city}, {self.country}"])
@dataclass
class Checkout:
cart: Cart
address: Address
def is_domestic(self):
return self.address.country == "NL"
before = CheckoutBefore()
for name, cents in [("lamp", 3999), ("bulb", 499)]:
before.add_item(name, cents)
before.apply_coupon(10)
before.set_address("Ada", "Keizersgracht 1", "Amsterdam", "NL")
cart = Cart()
for name, cents in [("lamp", 3999), ("bulb", 499)]:
cart.add(name, cents)
cart.apply_coupon(10)
after = Checkout(cart, Address("Ada", "Keizersgracht 1", "Amsterdam", "NL"))
assert after.cart.total == before.cart_total() == 4048
assert after.address.label == before.shipping_label()
assert after.is_domestic() == before.is_domestic()
print("checkout: tests pass")
checkout: tests pass
Addressis a frozen dataclass. Its four fields are set together in the constructor, so there is no state where the street is set and the city is not.Cartkeeps its list behind an underscore and offersadd,apply_couponandtotal. It has state that changes, so it is a plain class.
import java.util.ArrayList;
import java.util.List;
public class Main {
// Before: one class, two jobs, and fields with prefixes.
static final class CheckoutBefore {
private final List<Integer> cartItems = new ArrayList<>();
private Integer cartCoupon;
private String shipName, shipStreet, shipCity, shipCountry;
void addItem(String name, int cents) { cartItems.add(cents); }
void applyCoupon(int percent) { cartCoupon = percent; }
int cartTotal() {
int sum = cartItems.stream().mapToInt(Integer::intValue).sum();
return cartCoupon == null ? sum : sum - Math.round(sum * cartCoupon / 100f);
}
void setAddress(String name, String street, String city, String country) {
shipName = name; shipStreet = street; shipCity = city; shipCountry = country;
}
String shippingLabel() { return shipName + "\n" + shipStreet + "\n" + shipCity + ", " + shipCountry; }
boolean isDomestic() { return "NL".equals(shipCountry); }
}
// After: each group of fields has a class, and the checkout uses both.
static final class Cart {
private final List<Integer> items = new ArrayList<>();
private Integer coupon;
void add(String name, int cents) { items.add(cents); }
void applyCoupon(int percent) { coupon = percent; }
int total() {
int sum = items.stream().mapToInt(Integer::intValue).sum();
return coupon == null ? sum : sum - Math.round(sum * coupon / 100f);
}
}
record Address(String name, String street, String city, String country) {
String label() { return name + "\n" + street + "\n" + city + ", " + country; }
}
record Checkout(Cart cart, Address address) {
boolean isDomestic() { return address.country().equals("NL"); }
}
public static void main(String[] args) {
CheckoutBefore before = new CheckoutBefore();
before.addItem("lamp", 3999);
before.addItem("bulb", 499);
before.applyCoupon(10);
before.setAddress("Ada", "Keizersgracht 1", "Amsterdam", "NL");
Cart cart = new Cart();
cart.add("lamp", 3999);
cart.add("bulb", 499);
cart.applyCoupon(10);
Checkout after = new Checkout(cart, new Address("Ada", "Keizersgracht 1", "Amsterdam", "NL"));
if (after.cart().total() != before.cartTotal() || after.cart().total() != 4048) throw new AssertionError("total");
if (!after.address().label().equals(before.shippingLabel())) throw new AssertionError("label");
if (after.isDomestic() != before.isDomestic()) throw new AssertionError("domestic");
System.out.println("checkout: tests pass");
}
}
checkout: tests pass
Addressis a record, so it gets its constructor, accessors,equalsandhashCodefrom one line, and its fields are final.- In the first version the four address fields can be
nulluntilsetAddressruns. In the second version anAddressalways has all four.
package main
import (
"fmt"
"strings"
)
// Before: one type, two jobs, and fields with prefixes.
type checkoutBefore struct {
cartItems []int
cartCoupon int // 0 means no coupon
shipName, shipStreet, shipCity, shipCountry string
}
func (c *checkoutBefore) addItem(name string, cents int) { c.cartItems = append(c.cartItems, cents) }
func (c *checkoutBefore) applyCoupon(percent int) { c.cartCoupon = percent }
func (c *checkoutBefore) cartTotal() int {
sum := 0
for _, x := range c.cartItems {
sum += x
}
return sum - (sum*c.cartCoupon+50)/100
}
func (c *checkoutBefore) shippingLabel() string {
return strings.Join([]string{c.shipName, c.shipStreet, c.shipCity + ", " + c.shipCountry}, "\n")
}
func (c *checkoutBefore) isDomestic() bool { return c.shipCountry == "NL" }
// After: each group of fields has a type, and the checkout uses both.
type cart struct {
items []int
coupon int
}
func (c *cart) add(name string, cents int) { c.items = append(c.items, cents) }
func (c *cart) applyCoupon(percent int) { c.coupon = percent }
func (c *cart) total() int {
sum := 0
for _, x := range c.items {
sum += x
}
return sum - (sum*c.coupon+50)/100
}
type address struct{ name, street, city, country string }
func (a address) label() string {
return strings.Join([]string{a.name, a.street, a.city + ", " + a.country}, "\n")
}
type checkout struct {
cart *cart
address address
}
func (c checkout) isDomestic() bool { return c.address.country == "NL" }
func main() {
before := &checkoutBefore{}
before.addItem("lamp", 3999)
before.addItem("bulb", 499)
before.applyCoupon(10)
before.shipName, before.shipStreet, before.shipCity, before.shipCountry = "Ada", "Keizersgracht 1", "Amsterdam", "NL"
c := &cart{}
c.add("lamp", 3999)
c.add("bulb", 499)
c.applyCoupon(10)
after := checkout{c, address{"Ada", "Keizersgracht 1", "Amsterdam", "NL"}}
if after.cart.total() != before.cartTotal() || after.cart.total() != 4048 {
panic("total")
}
if after.address.label() != before.shippingLabel() || after.isDomestic() != before.isDomestic() {
panic("address")
}
fmt.Println("checkout: tests pass")
}
checkout: tests pass
addressis a small value type with no pointer, so a copy of it is a full, independent address.carthas state that changes, so the checkout holds a pointer to it, and its methods have pointer receivers.
Consequences
Each class is small enough to read at once, and each one changes for one kind of reason. The parts can be reused and tested alone.
The cost is more classes and more names. A reader who wants to see all of checkout must open three files, not one. The split pays when the groups really are separate; a split along a line that the code crosses often only spreads one job across two classes, and the next change will be Shotgun Surgery.
Size alone is not the smell. A class with many fields that all describe one thing, such as a record for a row with forty columns, may be large and still be one idea. The test is whether the fields and methods fall into groups that do not use each other.
How to fix it
- Fields that share a prefix or are used together: Extract Class.1
- Fields and methods used only by some kinds of object: Replace Type Code with Subclasses or Extract Superclass.1
- Methods that repeat the same steps: Extract Function first, then split.1
- Clients that use different parts of the class: split along the line between those parts.1
Variants and related patterns
Long Function. The same problem at the scale of one function. See Long Function.
Divergent Change. A large class is often the place where one class changes for many reasons. See Divergent Change.
Data Clumps. A group of fields that always go together is the first candidate for Extract Class. See Data Clumps.
God object. The extreme form, where one object knows and does most of the program. See God object.
References
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Large Class
- Wikipedia, God object, revision 1352397558, the introduction and Characteristics
- Martin Fowler, Catalog of Refactorings, the cards Extract Class, Extract Superclass, Replace Type Code with Subclasses (alias Extract Subclass) and Extract Function
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Large Class
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag V7JA1C Edit this page History Report an error Markdown