Programming Search⌘K

Patterncore

Data Class

Also called anemic class, dumb data holder.

A code smell: a class has fields and accessors and no behaviour, while the rules about its data live in the classes that use it, often copied in several places.

Family
code-smell
Intent
Find the code that other classes run on a data class, and move it into the data class, so that the data and the rules about it are in one place.

Intent

Find the classes that only hold data, with getters and setters and nothing else. Look at the code that uses those getters and setters in other classes. Move that code into the data class, so that the class owns the rules about its own fields, and remove the setters that the rules make unnecessary.

Problem

A class that only holds data is not wrong in itself. It becomes a smell when the rules about the data are somewhere else: in a service, in a controller, or in three places that each work out the same thing from the same fields.

Refactoring describes data classes as classes with fields and accessors and nothing else, which other classes manipulate in too much detail. It notes that such a class is often a sign that behaviour is in the wrong place.1 Fowler's article on the Anemic Domain Model describes the same problem for a whole design: objects named after the business concepts that turn out to be "little more than bags of getters and setters", while "a set of service objects" holds the logic. He calls the result "really just a procedural style design".2

The forces are these:

  • A data class is quick to write and quick to map to a database row or a JSON document. Its behaviour has to go somewhere, and the first caller is the closest place.
  • Each caller that needs the same rule writes it again. The copies drift, and the result is Duplicated Code and Shotgun Surgery.
  • Public setters let any code change any field at any time. The class cannot keep a rule across its fields, such as an end date that is after the start date.
  • Each method elsewhere that reads several getters of the data class is a case of Feature Envy.

Solution

Refactoring gives the moves.1 The catalogue at refactoring.com has a card for each refactoring.3

  1. Close the fields: Encapsulate Record for public fields, so that all access goes through the class.
  2. Remove the setters that should not exist: Remove Setting Method for each field that must not change after construction.
  3. Find the users: look for the code in other classes that reads the getters and setters.
  4. Move the behaviour in: Move Function to bring that code into the data class. If only part of a function belongs there, use Extract Function first, then move the part.

The first edition gives the same steps, and compares data classes to children: a fine place to start, but they must take on some responsibility to grow up.4

Refactoring also names an exception. A record that holds the result of one phase for the next phase, as made by Split Phase, is a data class by design, and it is fine when it is immutable.1 Languages now have a construct for this case. JEP 395 describes Java records as "classes that act as transparent carriers for immutable data", and the Python dataclasses module adds "generated special methods such as __init__() and __repr__()" to such classes.56 A record with no behaviour is not a smell when its job is to carry values.

Example

A subscription is a class with a start, an end and setters. Billing and reminders each compute from the fields whether the subscription is active and how many days are left, and a renewal sets the end date from outside.

import assert from "node:assert/strict";

const DAY = 24 * 60 * 60 * 1000;
const d = (s) => Date.parse(`${s}T00:00:00Z`);

// Before: a data class, and the rules in the code that uses it.
class SubscriptionBefore {
  constructor(start, end) { this.start = start; this.end = end; }
  getStart() { return this.start; }
  getEnd() { return this.end; }
  setEnd(end) { this.end = end; }
}
const billingActive = (s, day) => s.getStart() <= day && day < s.getEnd();
const reminderDaysLeft = (s, day) => Math.max(0, Math.ceil((s.getEnd() - day) / DAY));
function renewBefore(s, days) { s.setEnd(s.getEnd() + days * DAY); }

// After: the rules are methods, and a renewal makes a value.
class Subscription {
  #start;
  #end;
  constructor(start, end) {
    if (end <= start) throw new RangeError("end must be after start");
    this.#start = start;
    this.#end = end;
  }
  isActive(day) { return this.#start <= day && day < this.#end; }
  daysLeft(day) { return Math.max(0, Math.ceil((this.#end - day) / DAY)); }
  renewed(days) { return new Subscription(this.#start, this.#end + days * DAY); }
}

const old = new SubscriptionBefore(d("2026-01-01"), d("2026-02-01"));
const sub = new Subscription(d("2026-01-01"), d("2026-02-01"));
for (const day of [d("2025-12-31"), d("2026-01-20"), d("2026-02-01")]) {
  assert.equal(sub.isActive(day), billingActive(old, day));
  assert.equal(sub.daysLeft(day), reminderDaysLeft(old, day));
}
renewBefore(old, 30);
const next = sub.renewed(30);
assert.equal(next.daysLeft(d("2026-02-01")), reminderDaysLeft(old, d("2026-02-01")));
assert.equal(sub.daysLeft(d("2026-02-01")), 0); // the old value is unchanged
assert.throws(() => new Subscription(d("2026-02-01"), d("2026-01-01")), RangeError);
console.log("subscription: tests pass");
Output
subscription: tests pass

In the second version billing and reminders call isActive and daysLeft, and the rule for each is in one place. The class can check that the end is after the start, because no setter can break that rule after construction. A renewal returns a value, so code that holds the old subscription is not surprised by a change.

Language What the example shows
JavaScript the rules moved in, the setter removed, as above
Python a frozen dataclass with methods, and dataclasses.replace for the renewal
Java a record with a compact constructor that checks the rule, and methods
Go a struct with unexported fields, a constructor function and methods
PythonGitHub
import dataclasses
from dataclasses import dataclass
from datetime import date, timedelta


# Before: a data class, and the rules in the code that uses it.
class SubscriptionBefore:
    def __init__(self, start, end):
        self.start = start
        self.end = end


def billing_active(s, day):
    return s.start <= day < s.end


def reminder_days_left(s, day):
    return max(0, (s.end - day).days)


def renew_before(s, days):
    s.end = s.end + timedelta(days=days)


# After: a frozen dataclass that owns its rules.
@dataclass(frozen=True)
class Subscription:
    start: date
    end: date

    def __post_init__(self):
        if self.end <= self.start:
            raise ValueError("end must be after start")

    def is_active(self, day):
        return self.start <= day < self.end

    def days_left(self, day):
        return max(0, (self.end - day).days)

    def renewed(self, days):
        return dataclasses.replace(self, end=self.end + timedelta(days=days))


old = SubscriptionBefore(date(2026, 1, 1), date(2026, 2, 1))
sub = Subscription(date(2026, 1, 1), date(2026, 2, 1))
for day in [date(2025, 12, 31), date(2026, 1, 20), date(2026, 2, 1)]:
    assert sub.is_active(day) == billing_active(old, day)
    assert sub.days_left(day) == reminder_days_left(old, day)

renew_before(old, 30)
nxt = sub.renewed(30)
assert nxt.days_left(date(2026, 2, 1)) == reminder_days_left(old, date(2026, 2, 1)) == 30
assert sub.days_left(date(2026, 2, 1)) == 0
try:
    sub.end = date(2027, 1, 1)
    raise AssertionError("a frozen dataclass must not allow assignment")
except dataclasses.FrozenInstanceError:
    pass
try:
    Subscription(date(2026, 2, 1), date(2026, 1, 1))
    raise AssertionError("the rule must be checked")
except ValueError:
    pass
print("subscription: tests pass")
Output
subscription: tests pass
  • frozen=True makes assignment to a field raise FrozenInstanceError, which removes the setters.
  • __post_init__ runs after the generated __init__, so the class can check its rule once, at construction.
  • dataclasses.replace makes a copy with some fields changed, and runs __post_init__ again on the copy.
JavaGitHub
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

public class Main {
    // Before: a data class, and the rules in the code that uses it.
    static final class SubscriptionBefore {
        private LocalDate start, end;
        SubscriptionBefore(LocalDate start, LocalDate end) { this.start = start; this.end = end; }
        LocalDate getStart() { return start; }
        LocalDate getEnd() { return end; }
        void setEnd(LocalDate end) { this.end = end; }
    }

    static boolean billingActive(SubscriptionBefore s, LocalDate day) {
        return !day.isBefore(s.getStart()) && day.isBefore(s.getEnd());
    }

    static long reminderDaysLeft(SubscriptionBefore s, LocalDate day) {
        return Math.max(0, ChronoUnit.DAYS.between(day, s.getEnd()));
    }

    // After: a record that checks its rule and owns its behaviour.
    record Subscription(LocalDate start, LocalDate end) {
        Subscription {
            if (!end.isAfter(start)) throw new IllegalArgumentException("end must be after start");
        }

        boolean isActive(LocalDate day) { return !day.isBefore(start) && day.isBefore(end); }
        long daysLeft(LocalDate day) { return Math.max(0, ChronoUnit.DAYS.between(day, end)); }
        Subscription renewed(int days) { return new Subscription(start, end.plusDays(days)); }
    }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    public static void main(String[] args) {
        LocalDate jan1 = LocalDate.of(2026, 1, 1), feb1 = LocalDate.of(2026, 2, 1);
        SubscriptionBefore old = new SubscriptionBefore(jan1, feb1);
        Subscription sub = new Subscription(jan1, feb1);
        for (LocalDate day : List.of(LocalDate.of(2025, 12, 31), LocalDate.of(2026, 1, 20), feb1)) {
            check(sub.isActive(day) == billingActive(old, day), "active " + day);
            check(sub.daysLeft(day) == reminderDaysLeft(old, day), "days left " + day);
        }
        old.setEnd(old.getEnd().plusDays(30));
        Subscription next = sub.renewed(30);
        check(next.daysLeft(feb1) == reminderDaysLeft(old, feb1) && next.daysLeft(feb1) == 30, "renewed");
        check(sub.daysLeft(feb1) == 0, "old value unchanged");
        try {
            new Subscription(feb1, jan1);
            throw new AssertionError("the rule must be checked");
        } catch (IllegalArgumentException expected) {
        }
        System.out.println("subscription: tests pass");
    }
}
Output
subscription: tests pass
  • The compact constructor Subscription { ... } runs before the fields are set, so every record of this type has an end after its start.
  • A record's fields are final and it has no setters, so renewed returns a record and leaves the original as it was.
  • LocalDate is itself an immutable value type, so plusDays also returns a value.
package main

import (
	"errors"
	"fmt"
	"time"
)

func d(s string) time.Time {
	t, err := time.Parse(time.DateOnly, s)
	if err != nil {
		panic(err)
	}
	return t
}

const day = 24 * time.Hour

// Before: a data struct with exported fields, and the rules in the code that uses it.
type SubscriptionBefore struct{ Start, End time.Time }

func billingActive(s SubscriptionBefore, t time.Time) bool {
	return !t.Before(s.Start) && t.Before(s.End)
}
func reminderDaysLeft(s SubscriptionBefore, t time.Time) int {
	return max(0, int(s.End.Sub(t)/day))
}

// After: unexported fields, a constructor that checks the rule, and methods.
type Subscription struct{ start, end time.Time }

var errEnd = errors.New("end must be after start")

func NewSubscription(start, end time.Time) (Subscription, error) {
	if !end.After(start) {
		return Subscription{}, errEnd
	}
	return Subscription{start, end}, nil
}

func (s Subscription) IsActive(t time.Time) bool { return !t.Before(s.start) && t.Before(s.end) }
func (s Subscription) DaysLeft(t time.Time) int  { return max(0, int(s.end.Sub(t)/day)) }
func (s Subscription) Renewed(days int) Subscription {
	return Subscription{s.start, s.end.AddDate(0, 0, days)}
}

func main() {
	old := SubscriptionBefore{d("2026-01-01"), d("2026-02-01")}
	sub, err := NewSubscription(d("2026-01-01"), d("2026-02-01"))
	if err != nil {
		panic(err)
	}
	for _, t := range []time.Time{d("2025-12-31"), d("2026-01-20"), d("2026-02-01")} {
		if sub.IsActive(t) != billingActive(old, t) || sub.DaysLeft(t) != reminderDaysLeft(old, t) {
			panic("rules differ at " + t.Format(time.DateOnly))
		}
	}
	old.End = old.End.AddDate(0, 0, 30)
	next := sub.Renewed(30)
	if next.DaysLeft(d("2026-02-01")) != reminderDaysLeft(old, d("2026-02-01")) || sub.DaysLeft(d("2026-02-01")) != 0 {
		panic("renewal")
	}
	if _, err := NewSubscription(d("2026-02-01"), d("2026-01-01")); !errors.Is(err, errEnd) {
		panic("the rule must be checked")
	}
	fmt.Println("subscription: tests pass")
}
Output
subscription: tests pass
  • Go has no constructors. A function such as NewSubscription that returns a value and an error is the usual way to check a rule at creation. In this one-file example main could still write Subscription{} directly; the protection is real when the type is in its own package.
  • The methods have value receivers, and Renewed returns a value, so a Subscription behaves as an immutable value.
  • max is a built-in function since Go 1.21.

Consequences

The rules about the data are next to the data, and each one is written once. The class can protect its own rules, and a reader who wants to know what a subscription can do finds it in one file.

The class grows, and it must take care not to grow into a Large Class. Only the rules about the class's own data belong in it. Code that coordinates several objects, or that talks to a database or a screen, belongs elsewhere; Fowler's article makes the same point about keeping persistence and presentation in their own layers.2

Some data classes are right as they are. A message between services, a row read from a file, or a result passed from one phase to the next is data on purpose, and the code that uses it is in the phase that reads it. Make such classes immutable, so that their lack of behaviour cannot become a lack of control.

How to fix it

Feature Envy. The methods that use a data class's getters are envious of it. Moving them in fixes both smells. See Feature Envy.

Anemic Domain Model. The same problem across a whole model, where all the logic is in services. Fowler's article describes it.2

Immutability. A data class that cannot change is safe to share, which makes it the correct form for the cases that should stay data. See Immutability.

References

  1. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Data Class
  2. Martin Fowler, Anemic Domain Model, bliki, 2003, the whole article
  3. Martin Fowler, Catalog of Refactorings, the cards Encapsulate Record, Remove Setting Method, Move Function, Extract Function and Split Phase
  4. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Data Class
  5. JEP 395, Records, Summary, Goals and Motivation
  6. Python documentation, dataclasses, the introduction and frozen instances

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/YNY5BB/text.yaml