A Large Class is a class that does the work of several. It usually starts small and focused, then becomes the default place for anything loosely related: pricing next to scheduling, email next to CSV export, configuration next to business rules. The cost builds slowly. Every new feature means reading hundreds of lines to find the part that matters. Tests need a full object graph to check one calculation. Two developers working on unrelated features end up editing the same file and colliding in merges. In an interview, being able to spot the hidden classes inside a large one, and to explain the order in which you would pull them out, shows that you can think about design and not just syntax.
Signs
How to spot it in a review.
- The class has many fields, and each method uses only a small subset of them.
- Field names cluster by prefix or theme, such as
smtpHostandsentReminders, orvatRateandpayoutShare. - You can describe what the class does only with a sentence full of "and".
- Unit tests for one method need constructor arguments that the method never touches.
- The file is a merge-conflict hotspot for changes that have nothing to do with each other.
- Several methods would sit more naturally on a data object the class passes around.
What it looks like
A typical case, in three languages.
type Session = {
id: string;
tutorId: string;
studentEmail: string;
startsAt: Date;
minutes: number;
subject: string;
};
const DAY_MS = 24 * 60 * 60 * 1000;
function overlaps(a: Session, b: Session): boolean {
const aEnd = a.startsAt.getTime() + a.minutes * 60_000;
const bEnd = b.startsAt.getTime() + b.minutes * 60_000;
return a.startsAt.getTime() < bEnd && b.startsAt.getTime() < aEnd;
}
export class TutoringDesk {
private sessions: Session[] = [];
private hourlyRates = new Map<string, number>();
private payoutShare = 0.8;
private vatRate = 0.2;
private sentReminders = new Set<string>();
private exportDelimiter = ",";
constructor(private smtpHost: string) {}
setRate(tutorId: string, perHour: number): void {
this.hourlyRates.set(tutorId, perHour);
}
book(session: Session): void {
const clash = this.sessions.some(
(s) => s.tutorId === session.tutorId && overlaps(s, session),
);
if (clash) throw new Error(`Tutor ${session.tutorId} is busy`);
this.sessions.push(session);
}
priceFor(session: Session): number {
const rate = this.hourlyRates.get(session.tutorId) ?? 0;
return ((rate * session.minutes) / 60) * (1 + this.vatRate);
}
tutorPayout(tutorId: string): number {
const rate = this.hourlyRates.get(tutorId) ?? 0;
return this.sessions
.filter((s) => s.tutorId === tutorId)
.reduce((sum, s) => sum + ((rate * s.minutes) / 60) * this.payoutShare, 0);
}
reminderEmails(now: Date): string[] {
const messages: string[] = [];
for (const s of this.sessions) {
if (this.sentReminders.has(s.id)) continue;
const start = s.startsAt.getTime();
if (start > now.getTime() && start <= now.getTime() + DAY_MS) {
this.sentReminders.add(s.id);
messages.push(
`smtp://${this.smtpHost} -> ${s.studentEmail}: ${s.subject} at ${s.startsAt.toISOString()}`,
);
}
}
return messages;
}
exportCsv(): string {
const d = this.exportDelimiter;
const rows = [["id", "tutor", "start", "minutes", "price"].join(d)];
for (const s of this.sessions) {
rows.push(
[s.id, s.tutorId, s.startsAt.toISOString(), String(s.minutes), this.priceFor(s).toFixed(2)].join(d),
);
}
return rows.join("\n");
}
}from dataclasses import dataclass
from datetime import datetime, timedelta
@dataclass
class Session:
id: str
tutor_id: str
student_email: str
starts_at: datetime
minutes: int
subject: str
def overlaps(a: Session, b: Session) -> bool:
a_end = a.starts_at + timedelta(minutes=a.minutes)
b_end = b.starts_at + timedelta(minutes=b.minutes)
return a.starts_at < b_end and b.starts_at < a_end
class TutoringDesk:
def __init__(self, smtp_host: str) -> None:
self.sessions: list[Session] = []
self.hourly_rates: dict[str, float] = {}
self.payout_share = 0.8
self.vat_rate = 0.2
self.sent_reminders: set[str] = set()
self.export_delimiter = ","
self.smtp_host = smtp_host
def set_rate(self, tutor_id: str, per_hour: float) -> None:
self.hourly_rates[tutor_id] = per_hour
def book(self, session: Session) -> None:
clash = any(
s.tutor_id == session.tutor_id and overlaps(s, session)
for s in self.sessions
)
if clash:
raise ValueError(f"Tutor {session.tutor_id} is busy")
self.sessions.append(session)
def price_for(self, session: Session) -> float:
rate = self.hourly_rates.get(session.tutor_id, 0.0)
return rate * session.minutes / 60 * (1 + self.vat_rate)
def tutor_payout(self, tutor_id: str) -> float:
rate = self.hourly_rates.get(tutor_id, 0.0)
return sum(
rate * s.minutes / 60 * self.payout_share
for s in self.sessions
if s.tutor_id == tutor_id
)
def reminder_emails(self, now: datetime) -> list[str]:
messages: list[str] = []
for s in self.sessions:
if s.id in self.sent_reminders:
continue
if now < s.starts_at <= now + timedelta(hours=24):
self.sent_reminders.add(s.id)
messages.append(
f"smtp://{self.smtp_host} -> {s.student_email}: "
f"{s.subject} at {s.starts_at.isoformat()}"
)
return messages
def export_csv(self) -> str:
d = self.export_delimiter
rows = [d.join(["id", "tutor", "start", "minutes", "price"])]
for s in self.sessions:
rows.append(d.join([
s.id,
s.tutor_id,
s.starts_at.isoformat(),
str(s.minutes),
f"{self.price_for(s):.2f}",
]))
return "\n".join(rows)<?php
final class Session
{
public function __construct(
public readonly string $id,
public readonly string $tutorId,
public readonly string $studentEmail,
public readonly DateTimeImmutable $startsAt,
public readonly int $minutes,
public readonly string $subject,
) {
}
}
function overlaps(Session $a, Session $b): bool
{
$aEnd = $a->startsAt->modify("+{$a->minutes} minutes");
$bEnd = $b->startsAt->modify("+{$b->minutes} minutes");
return $a->startsAt < $bEnd && $b->startsAt < $aEnd;
}
final class TutoringDesk
{
/** @var Session[] */
private array $sessions = [];
/** @var array<string, float> */
private array $hourlyRates = [];
private float $payoutShare = 0.8;
private float $vatRate = 0.2;
/** @var array<string, true> */
private array $sentReminders = [];
private string $exportDelimiter = ',';
public function __construct(private string $smtpHost)
{
}
public function setRate(string $tutorId, float $perHour): void
{
$this->hourlyRates[$tutorId] = $perHour;
}
public function book(Session $session): void
{
foreach ($this->sessions as $s) {
if ($s->tutorId === $session->tutorId && overlaps($s, $session)) {
throw new RuntimeException("Tutor {$session->tutorId} is busy");
}
}
$this->sessions[] = $session;
}
public function priceFor(Session $session): float
{
$rate = $this->hourlyRates[$session->tutorId] ?? 0.0;
return $rate * $session->minutes / 60 * (1 + $this->vatRate);
}
public function tutorPayout(string $tutorId): float
{
$rate = $this->hourlyRates[$tutorId] ?? 0.0;
$sum = 0.0;
foreach ($this->sessions as $s) {
if ($s->tutorId === $tutorId) {
$sum += $rate * $s->minutes / 60 * $this->payoutShare;
}
}
return $sum;
}
/** @return string[] */
public function reminderEmails(DateTimeImmutable $now): array
{
$messages = [];
$horizon = $now->modify('+24 hours');
foreach ($this->sessions as $s) {
if (isset($this->sentReminders[$s->id])) {
continue;
}
if ($s->startsAt > $now && $s->startsAt <= $horizon) {
$this->sentReminders[$s->id] = true;
$messages[] = "smtp://{$this->smtpHost} -> {$s->studentEmail}: "
. "{$s->subject} at {$s->startsAt->format(DATE_ATOM)}";
}
}
return $messages;
}
public function exportCsv(): string
{
$d = $this->exportDelimiter;
$rows = [implode($d, ['id', 'tutor', 'start', 'minutes', 'price'])];
foreach ($this->sessions as $s) {
$rows[] = implode($d, [
$s->id,
$s->tutorId,
$s->startsAt->format(DATE_ATOM),
(string) $s->minutes,
number_format($this->priceFor($s), 2, '.', ''),
]);
}
return implode("\n", $rows);
}
}TutoringDesk belongs to a tutoring marketplace and handles four separate concerns: booking with clash detection, pricing and tutor payouts, reminder emails, and CSV export. The fields group cleanly by concern. hourlyRates, vatRate and payoutShare are used only by pricing. smtpHost and sentReminders are used only by reminders. exportDelimiter is used only by export. Changing the VAT rule means opening the same file that holds email formatting, and testing priceFor means building an object that needs an SMTP host.
Why it happens
How code ends up like this.
- Adding a method to an existing class is faster than deciding where a new class should live, so each shortcut feels harmless at the time.
- The class owns the central data, such as the session list, so every feature that touches that data gets pulled into it.
- Configuration values like rates and delimiters are stored as loose fields instead of in their own objects, which invites behaviour to gather around them.
- Nobody owns the design of the module, so no one notices when one class has become five.
Treatment
The refactorings that cure it, and when to choose each.
- Extract Class: Split a Class That Does Two Jobs
Fields and the methods that use them form a cluster. Pull
hourlyRates,vatRate,payoutShare,priceForandtutorPayoutinto aTutorPricingclass, andsmtpHostwithsentRemindersinto aReminderMailer. - Move Function: Put Behaviour Next to the Data It Uses
A method mostly reads another object's data. Overlap checking belongs on
Sessionor aTutorSchedule, and CSV formatting can move to aSessionCsvExporterthat receives a pricing object. - Replace Primitive with Object: Give Rule-Bearing Values a Type
Money and rates travel as bare floats. A
RateorMoneyvalue object gives pricing rules a natural home and keeps rounding in one place. - Separate Query from Modifier: Split Reads from State Changes
A method both returns data and changes state, as
reminderEmailsdoes when it marks reminders as sent. Split it so the extracted mailer has a clean query and an explicit command. - Extract function: give a fragment a name
A long method inside the class mixes several steps. Extracting them first makes the clusters visible before you move them to new classes.
Payoff
What you get once it's gone.
- Each new class has a single reason to change, so pricing changes no longer touch email code.
- Tests for one concern need only the collaborators that concern uses.
- Unrelated features stop colliding in the same file during merges.
- Names such as
TutorPricingandReminderMailerdocument the design better than one catch-all class.
When to leave it
Sometimes it's not worth fixing.
- A class whose many fields all serve one cohesive job, such as a configuration record or a generated data transfer object, is long but not large in the harmful sense.
- Framework entry points like a controller with several closely related actions can stay together if each action is thin and delegates elsewhere.
- If the class is scheduled for deletion or replacement soon, splitting it may cost more than it returns.
Common questions
Short answers to the usual doubts.
How many lines or fields make a class too large?
There is no reliable number. Look at cohesion instead: if groups of methods use disjoint sets of fields, the class holds several classes. A 400-line class with one focused job can be fine, while a 150-line class mixing billing and email is already a problem.
Where should I start when splitting a Large Class?
List the fields and mark which methods use each one. The clusters that appear are your candidate classes. Extract the cluster with the fewest connections to the rest first, keep the original class delegating to it, run the tests, then continue with the next cluster.
Is Large Class the same as a God Object?
They overlap. A God Object is an extreme Large Class that also knows about and controls much of the rest of the system. Every God Object is a Large Class, but a Large Class can be self-contained and still need splitting.
Won't extracting classes just spread the complexity around?
The total amount of logic stays the same, but each piece becomes readable and testable on its own. The original class becomes a small coordinator, and you can reason about pricing without reading email code. If an extracted class ends up doing almost nothing, inline it back.
How do I talk about this smell in an interview?
Point to concrete evidence such as field clusters and tests that need irrelevant setup, name the classes you would extract, and explain the order and how you keep behaviour unchanged with tests at each step. Interviewers care more about a safe incremental plan than a perfect final diagram.