A data class has fields, getters, often setters, and nothing else. Every decision about that data is made somewhere else: a service, a controller, a cron job. Each of those callers pulls values out, runs its own calculation and sometimes writes the result back through a setter. The class looks harmless because it is small. The cost is spread across the codebase. The rules that belong to the concept are duplicated in several places, they drift apart, and nothing stops a caller from putting the object into a state that makes no sense. In an interview, this smell often comes up as the anemic domain model. You are expected to explain why behaviour should live with the data it depends on, and also to say when a plain data carrier is the right choice.
Signs
How to spot it in a review.
- The class has only a constructor, getters and setters, with no methods that make a decision or enforce a rule.
- Several services call three or four getters on the same object in a row and then compute something from the results.
- The same calculation, such as an overdue check or a fee formula, appears in more than one caller with small differences.
- Public setters let any caller change a field that should only change as part of a business event.
- Unit tests for the concept sit next to service classes, because the class itself has nothing to test.
What it looks like
A typical case, in three languages.
export class RentalAgreement {
constructor(
private toolSku: string,
private dailyRateCents: number,
private depositCents: number,
private dueAt: Date,
private returnedAt: Date | null = null,
private damageReported = false,
) {}
getToolSku(): string { return this.toolSku; }
getDailyRateCents(): number { return this.dailyRateCents; }
getDepositCents(): number { return this.depositCents; }
getDueAt(): Date { return this.dueAt; }
getReturnedAt(): Date | null { return this.returnedAt; }
setReturnedAt(value: Date): void { this.returnedAt = value; }
isDamageReported(): boolean { return this.damageReported; }
setDamageReported(value: boolean): void { this.damageReported = value; }
}
const DAY_MS = 24 * 60 * 60 * 1000;
const LATE_RATE_PERCENT = 150;
export class ReturnDeskService {
lateFeeCents(agreement: RentalAgreement): number {
const returnedAt = agreement.getReturnedAt();
if (returnedAt === null) return 0;
const lateMs = returnedAt.getTime() - agreement.getDueAt().getTime();
if (lateMs <= 0) return 0;
const lateDays = Math.ceil(lateMs / DAY_MS);
return Math.floor((lateDays * agreement.getDailyRateCents() * LATE_RATE_PERCENT) / 100);
}
depositRefundCents(agreement: RentalAgreement): number {
if (agreement.isDamageReported()) return 0;
return Math.max(0, agreement.getDepositCents() - this.lateFeeCents(agreement));
}
}
export class OverdueReminderJob {
isOverdue(agreement: RentalAgreement, now: Date): boolean {
return agreement.getReturnedAt() === null && now.getTime() > agreement.getDueAt().getTime();
}
}import math
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
DAY_SECONDS = 24 * 60 * 60
LATE_RATE_PERCENT = 150
@dataclass
class RentalAgreement:
tool_sku: str
daily_rate_cents: int
deposit_cents: int
due_at: datetime
returned_at: Optional[datetime] = None
damage_reported: bool = False
class ReturnDeskService:
def late_fee_cents(self, agreement: RentalAgreement) -> int:
if agreement.returned_at is None:
return 0
late_seconds = (agreement.returned_at - agreement.due_at).total_seconds()
if late_seconds <= 0:
return 0
late_days = math.ceil(late_seconds / DAY_SECONDS)
return (late_days * agreement.daily_rate_cents * LATE_RATE_PERCENT) // 100
def deposit_refund_cents(self, agreement: RentalAgreement) -> int:
if agreement.damage_reported:
return 0
return max(0, agreement.deposit_cents - self.late_fee_cents(agreement))
class OverdueReminderJob:
def is_overdue(self, agreement: RentalAgreement, now: datetime) -> bool:
return agreement.returned_at is None and now > agreement.due_at<?php
final class RentalAgreement
{
public function __construct(
private string $toolSku,
private int $dailyRateCents,
private int $depositCents,
private DateTimeImmutable $dueAt,
private ?DateTimeImmutable $returnedAt = null,
private bool $damageReported = false,
) {}
public function getToolSku(): string { return $this->toolSku; }
public function getDailyRateCents(): int { return $this->dailyRateCents; }
public function getDepositCents(): int { return $this->depositCents; }
public function getDueAt(): DateTimeImmutable { return $this->dueAt; }
public function getReturnedAt(): ?DateTimeImmutable { return $this->returnedAt; }
public function setReturnedAt(DateTimeImmutable $value): void { $this->returnedAt = $value; }
public function isDamageReported(): bool { return $this->damageReported; }
public function setDamageReported(bool $value): void { $this->damageReported = $value; }
}
const DAY_SECONDS = 24 * 60 * 60;
const LATE_RATE_PERCENT = 150;
final class ReturnDeskService
{
public function lateFeeCents(RentalAgreement $agreement): int
{
$returnedAt = $agreement->getReturnedAt();
if ($returnedAt === null) {
return 0;
}
$lateSeconds = $returnedAt->getTimestamp() - $agreement->getDueAt()->getTimestamp();
if ($lateSeconds <= 0) {
return 0;
}
$lateDays = (int) ceil($lateSeconds / DAY_SECONDS);
return intdiv($lateDays * $agreement->getDailyRateCents() * LATE_RATE_PERCENT, 100);
}
public function depositRefundCents(RentalAgreement $agreement): int
{
if ($agreement->isDamageReported()) {
return 0;
}
return max(0, $agreement->getDepositCents() - $this->lateFeeCents($agreement));
}
}
final class OverdueReminderJob
{
public function isOverdue(RentalAgreement $agreement, DateTimeImmutable $now): bool
{
return $agreement->getReturnedAt() === null
&& $now->getTimestamp() > $agreement->getDueAt()->getTimestamp();
}
}This is from a tool-rental shop's back office. RentalAgreement knows its due date, rate and deposit but cannot answer a single question about itself. ReturnDeskService and OverdueReminderJob each read its fields and rebuild part of the rental rules. Nothing prevents a caller from setting returnedAt without recording damage, or from marking damage on a rental that was never returned. The fix is to move lateFeeCents, depositRefundCents and isOverdue onto RentalAgreement and replace both setters with a single markReturned(at, damaged) method.
Why it happens
How code ends up like this.
- Scattered rules drift apart. When the late rate changes from 150 to 175 percent, you have to find every caller that recomputes the fee, and you will miss one.
- Public setters let any code put the object into an invalid state, so every caller has to guard against states the class should have made impossible.
- Callers become coupled to the internal shape of the data. Renaming or retyping a field breaks code in services that have nothing to do with that change.
- The concept is hard to test in isolation, because its behaviour only exists inside services that come with their own dependencies.
Treatment
The refactorings that cure it, and when to choose each.
- Move Function: Put Behaviour Next to the Data It Uses
A caller computes something using only the data class's fields, like
lateFeeCentsorisOverdue. Move that function onto the class and have the caller delegate to it. - Extract function: give a fragment a name
The logic is buried inside a longer service method. Extract the part that uses the data class first so it can then be moved as one unit.
- Change Function Declaration: Fix a Signature Without Breaking Callers
Paired setters really represent a single business event. Replace
setReturnedAtandsetDamageReportedwithmarkReturned(at, damaged), which can validate the transition. - Replace Primitive with Object: Give Rule-Bearing Values a Type
Fields such as cents amounts or date ranges carry their own rules. Wrap them in a
MoneyorRentalPeriodtype so arithmetic and comparisons live in one place. - Hide Delegate: Stop Callers Reaching Through an Object's Internals
Callers reach through the data class to call methods on its fields. Add a method on the class that answers the question directly.
- Extract Class: Split a Class That Does Two Jobs
Once behaviour moves in, the class may grow two clear responsibilities, for example pricing and lifecycle. Split them so that each stays cohesive.
Payoff
What you get once it's gone.
- Each rule exists in exactly one place, so a policy change is a single edit with a single test.
- The class can guard its own invariants, which removes defensive checks from every caller.
- Services get shorter and describe workflow instead of re-deriving domain facts.
- The domain concept becomes testable with plain unit tests and no mocks.
When to leave it
Sometimes it's not worth fixing.
- DTOs at system boundaries, such as API request and response bodies, queue messages or ORM row mappings, are meant to carry data. Keep them dumb and map them into richer domain objects.
- Read models and reporting projections built purely for display rarely have behaviour worth moving into them.
- Immutable records or value types whose only job is grouping a few values are fine without methods, as long as no caller keeps rebuilding the same logic around them.
- In a codebase built around functional style, data and functions are deliberately kept apart. The smell there is scattered or duplicated functions, not the absence of methods.
Common questions
Short answers to the usual doubts.
Is every class with only getters a code smell?
No. A data class is a smell when real domain rules about that data live in other classes, especially when those rules are duplicated. A DTO that crosses a process boundary, or an immutable record used for grouping values, is doing its job. The question to ask is whether any code outside the class keeps making decisions that are about the class's own data.
How does this relate to the anemic domain model?
An anemic domain model is the data class smell applied to a whole layer. Every entity is a bag of fields, and every rule sits in service classes. The treatment is the same, just at a larger scale: move behaviour that depends on an entity's state onto that entity, and let services coordinate entities instead of computing their internals.
Are Python dataclasses or TypeScript interfaces a problem by themselves?
No. @dataclass and plain interfaces are just convenient ways to declare fields. You can add methods to a dataclass, and you can pair an interface with a module of functions that own the rules. The smell is about where the logic lives and whether it is duplicated, not about which language feature declares the fields.
How do I talk about this smell in an interview?
Name it, point to the evidence, and propose a move. For example: three services read the agreement's due date and compare it with now, so isOverdue belongs on the agreement. Then mention the counterpoint: you would keep the API payload as a plain DTO and map it into the domain object. Showing that you know both sides comes across better than a blanket rule.
Should I remove all setters?
Remove setters that let callers bypass a business rule, and replace them with intention-revealing methods such as markReturned or extendDueDate. Keep a setter only when the field truly has no constraints and changing it is not a meaningful domain event. Constructors and factory methods should handle initial state.