Skip to content

Data Class: Fields and Getters With the Logic Living Elsewhere

How to spot a data class that only holds fields and accessors, why it scatters business rules, and how to move behaviour back next to the data.

7 min readCode smellDead weight

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();
  }
}

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.

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.

Next guide6 of 6 · Smells: dead weightExplaining Comments: When a Comment Covers for Unclear CodeRead the next one