Video in progress

Strong Middle 🧱 OOP and SOLID

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 an Email object, it is valid;
  • currency and rounding rules live inside Money, so you don't have to setScale(2, HALF_UP) on a BigDecimal everywhere;
  • the code documents itself.

In practice:

  • in JPA you store them with @Embeddable or an AttributeConverter;
  • Jackson handles records well, and for a single-field type you can add @JsonValue to keep the plain string form in JSON;
  • in Spring MVC, for @PathVariable AccountId id you register a Converter<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.