Building a banking platform that could mimic real-world banking app requires modeling accounts and money the way the real world treats them: an account is one specific account forever, while ten dollars is just ten dollars.
I'd like to elaborate on these terms:
Aggregate, Invariant, Entity, Value Object, using the example from my banking project - Account.java (Aggregate root, Entity) & Money.java (Value Object)
1. Invariant
It is something that is always true;
For example,
"only ACTIVE accounts can be frozen"
"account with a non-zero balance cannot be closed"
"a withdrawal amount must be positive"
"money moves only on ACTIVE accounts"
Invariants live inside the aggregate, in the domain layer, checked before every state change.
public void withdraw(Money amount) { if (status != AccountStatus.ACTIVE) { throw new IllegalStateException("money moves only on ACTIVE accounts"); } if (!amount.isPositive()) { throw new IllegalArgumentException( "a withdrawal amount must be positive" ); } Money remaining = balance.subtract(amount); if (remaining.isNegative()) { throw new IllegalStateException( "insufficient funds: balance " + balance.amount() + ", requested " + amount.amount() ); } this.balance = remaining; } 2. Aggregate, Aggregate root
An aggregate is a cluster of domain objects treated as one unit;
An aggregate root is the only entry point - everything inside is private. Outside code - handlers, controllers, other slices - holds a reference to the root and can only ask it to do things through its methods. It cannot reach in and change the insides directly.
In my banking platform: Account.java - is an aggregate root:
- all fields are private
- getters let you read, and no setters to avoid writing from outside;
- The only state changes are the behavior methods: deposit(), withdraw(), freeze(), unfreeze(), close();
- even creation goes through the root: private constructor, Account.open() is the one way in - the JPA constructor is protected so application code can't make blank accounts.
- the repository loads and saves the aggregate by the root's id as a whole - you never fetch or persist a piece of it separately.
If outside code could reach inside, the rules could be skipped. One entry point means every change passes the guard - that is how invariants stay true.
@Entity @Table(name = "accounts") public class Account { @Id private UUID id; @Column( name = "account_number", nullable = false, unique = true, updatable = false ) private AccountNumber accountNumber; @Column(name = "owner_id", nullable = false, updatable = false) private UUID ownerId; @Enumerated(EnumType.STRING) @Column(nullable = false, updatable = false) private AccountType type; @Enumerated(EnumType.STRING) @Column(nullable = false) private AccountStatus status; @Embedded @AttributeOverride( name = "amount", column = @Column(name = "balance_amount", nullable = false) ) @AttributeOverride( name = "currencyCode", column = @Column( name = "balance_currency", nullable = false, length = 3 ) ) private Money balance; @Version private long version; @Column(name = "created_at", nullable = false, updatable = false) private Instant createdAt; protected Account() { // required by JPA; protected so application code can't create blank accounts } private Account( UUID ownerId, AccountType type, String currencyCode, AccountNumber accountNumber ) { if (ownerId == null) { throw new IllegalArgumentException("ownerId is required"); } if (type == null) { throw new IllegalArgumentException("type is required"); } this.id = UUID.randomUUID(); this.accountNumber = accountNumber; this.ownerId = ownerId; this.type = type; this.status = AccountStatus.ACTIVE; this.balance = Money.zero(currencyCode); this.createdAt = Instant.now(); } public static Account open( UUID ownerId, AccountType type, String currencyCode, AccountNumber accountNumber ) { return new Account(ownerId, type, currencyCode, accountNumber); } public void freeze() { if (status != AccountStatus.ACTIVE) { throw new IllegalStateException( "only ACTIVE accounts can be frozen" ); } this.status = AccountStatus.FROZEN; } public void unfreeze() { if (status != AccountStatus.FROZEN) { throw new IllegalStateException( "only FROZEN account can be unfrozen" ); } this.status = AccountStatus.ACTIVE; } public void close() { if (status == AccountStatus.CLOSED) { throw new IllegalStateException("closed account cannot be closed"); } if (!balance.isZero()) { throw new IllegalStateException( "account with a non-zero balance cannot be closed" ); } this.status = AccountStatus.CLOSED; } public void deposit(Money amount) { if (status != AccountStatus.ACTIVE) { throw new IllegalStateException("money moves only on ACTIVE accounts"); } if (!amount.isPositive()) { throw new IllegalArgumentException( "deposit amount must be positive" ); } this.balance = balance.add(amount); } public void withdraw(Money amount) { if (status != AccountStatus.ACTIVE) { throw new IllegalStateException("money moves only on ACTIVE accounts"); } if (!amount.isPositive()) { throw new IllegalArgumentException( "a withdrawal amount must be positive" ); } Money remaining = balance.subtract(amount); if (remaining.isNegative()) { throw new IllegalStateException( "insufficient funds: balance " + balance.amount() + ", requested " + amount.amount() ); } this.balance = remaining; } public UUID getId() { return id; } public AccountNumber getAccountNumber() { return accountNumber; } public UUID getOwnerId() { return ownerId; } public AccountType getType() { return type; } public AccountStatus getStatus() { return status; } public Money getBalance() { return balance; } public Instant getCreatedAt() { return createdAt; } } 3. Entity vs. Value Object
What is the difference between an entity and a value object?
Entity has an identity (id) that persists over time - same Account through deposits, freezing, closing and etc. Two accounts with the same balance are still two different accounts.
A value object has no identity - it is defined entirely by its values.
Two Money(10, USD) are interchangeable.Value objects are immutable: you never change a Money, you replace it with a new one.
(balance.add(amount)); add() returns a new Money, and the old one is untouched.
In Java, a record is the natural way to build this, because it gives immutability and value-based equality for free.Value objects are equal by value: same amount + same currency = same Money
One detail in my Money class exists only to protect this — BigDecimal.equals compares scale, so 0 is not equal to 0.0000. The constructor normalizes every amount to scale 4, so equal amounts stay equal:
amount = amount.setScale(SCALE, RoundingMode.HALF_EVEN); Account.java - Entity
@Entity @Table(name = "accounts") public class Account { @Id private UUID id; ..... Money.java - Value Object
@Embeddable public record Money(BigDecimal amount, String currencyCode) { /** Storage scale — matches the numeric(19,4) columns money is persisted in. */ private static final int SCALE = 4; public Money { if (amount == null) { throw new IllegalArgumentException("amount is required"); } if (currencyCode == null || currencyCode.length() != 3) { throw new IllegalArgumentException( "currencyCode must be a 3-letter ISO code" ); } if (amount.scale() > SCALE) { throw new IllegalArgumentException( "amount supports at most 4 decimal places" ); } // Normalize scale so equal amounts are equal objects: BigDecimal.equals // compares scale, so without this 0 != 0.0000 and Money would break the // core value-object contract (and every DB round-trip comparison). amount = amount.setScale(SCALE, RoundingMode.HALF_EVEN); currencyCode = currencyCode.toUpperCase(Locale.ROOT); try { Currency.getInstance(currencyCode); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "currencyCode must be a valid ISO 4217 code: " + currencyCode, e ); } } public static Money zero(String currencyCode) { return new Money(BigDecimal.ZERO, currencyCode); } public Money add(Money other) { requireSameCurrency(other); return new Money(amount.add(other.amount), currencyCode); } public Money subtract(Money other) { requireSameCurrency(other); return new Money(amount.subtract(other.amount), currencyCode); } public boolean isNegative() { return amount.signum() < 0; } public boolean isZero() { return amount.signum() == 0; } public boolean isPositive() { return amount.signum() > 0; } private void requireSameCurrency(Money other) { if (!currencyCode.equals(other.currencyCode)) { throw new IllegalArgumentException( "currency mismatch: " + currencyCode + " vs " + other.currencyCode ); } } } Building this taught me that modeling is mostly about deciding where the rules live. In my banking platform, the rules live inside the aggregate: the account guards its own invariants, and money is just a value that gets replaced, never edited. An account is one specific account forever; ten dollars is just ten dollars.
