Video in progress
What is primitive obsession, and what bugs does it lead to?
It means expressing domain concepts (email, amount, id, phone) with plain String, long and BigDecimal. As a result, arguments get swapped, validation is scattered, and the compiler can't catch the mistake.
📖 Answer
A real kind of bug:
void transfer(long fromAccountId, long toAccountId, long amountTiyin) { ... }
transfer(toId, fromId, amount); // the money went the wrong way, and it compiled
Or:
void assign(long userId, long courseId);
assign(courseId, userId); // if the IDs happen to match in the test data, the test passes too
With value types:
public record AccountId(long value) {}
public record Email(String value) {
public Email {
if (value == null || !value.contains("@")) throw new IllegalArgumentException("Email noto'g'ri");
value = value.trim().toLowerCase();
}
}
void transfer(AccountId from, AccountId to, Money amount);
What we gain:
- if argument types get mixed up, it is a compile error;
- validation and normalization (
trim,toLowerCase) are in one place, and as long as there is anEmailobject, it is valid; - currency and rounding rules live inside
Money, so you don't have tosetScale(2, HALF_UP)on aBigDecimaleverywhere; - the code documents itself.
In practice:
- in JPA you store them with
@Embeddableor anAttributeConverter; - Jackson handles records well, and for a single-field type you can add
@JsonValueto keep the plain string form in JSON; - in Spring MVC, for
@PathVariable AccountId idyou register aConverter<String, AccountId>.
Don't wrap everything: an int i or a boolean in local calculations doesn't count. Wrap the concepts that cross boundaries and have rules.
Sign up to mark studied questions and save your progress.