Definition
- Domain model is a set of Java classes that represent business concepts (Account, Transfer, Loan) and enforce business rules (minimum balance, daily transfer limit, interest calculation).
- Business rules are constraints and logic that exist regardless of technology: an account cannot go below zero, a loan EMI depends on principal and interest rate.
- Infrastructure is anything technology-specific: database queries, HTTP endpoints, Kafka producers, JSON serialization.
- Hexagonal architecture places the domain at the center, defines ports (interfaces) for external communication, and uses adapters to connect to real infrastructure.
- Separation means the domain layer compiles and runs without importing Spring, JPA, Kafka, or any framework.
Think of a bank's rule book. The rule book says: a savings account must maintain a minimum balance of 5000 rupees, and a single transfer cannot exceed 10 lakh rupees. These rules exist on paper, independent of any computer system. Whether the bank uses Oracle or PostgreSQL, whether customers use a mobile app or a branch counter, the rules stay the same. Domain modeling puts those rules into Java classes. Infrastructure is the building: the counter, the ATM, the mobile app. The rules live in the book, not in the building. If you rebuild the building, the rules do not change.
Understanding the Concepts
What is a domain model?
A domain model is a collection of Java classes that represent the core business concepts and enforce business rules. In a banking application, the domain model includes entities like Account, Transfer, and Loan, value objects like Money and AccountNumber, and domain services like InterestCalculator.
The domain model is not about data storage. It is about behavior. An Account class does not just hold a balance. It enforces rules: you cannot withdraw more than the available balance, you cannot transfer to the same account, you cannot exceed the daily transfer limit.
package com.bank.domain;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class Account {
private final String accountId;
private final String holderName;
private BigDecimal balance;
private final BigDecimal minimumBalance;
private final LocalDateTime openedAt;
public Account(String accountId, String holderName,
BigDecimal initialBalance, BigDecimal minimumBalance) {
this.accountId = accountId;
this.holderName = holderName;
this.balance = initialBalance;
this.minimumBalance = minimumBalance;
this.openedAt = LocalDateTime.now();
}
// Business rule: balance cannot go below minimum
public void withdraw(BigDecimal amount) {
BigDecimal newBalance = balance.subtract(amount);
if (newBalance.compareTo(minimumBalance) < 0) {
throw new InsufficientBalanceException(
"Withdrawal of " + amount + " would leave balance "
+ newBalance + ", below minimum " + minimumBalance);
}
this.balance = newBalance;
}
public void deposit(BigDecimal amount) {
if (amount.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("Deposit amount must be positive");
}
this.balance = balance.add(amount);
}
public BigDecimal getBalance() { return balance; }
public String getAccountId() { return accountId; }
public String getHolderName() { return holderName; }
}
package com.bank.domain;
public class InsufficientBalanceException extends RuntimeException {
public InsufficientBalanceException(String message) {
super(message);
}
}
package com.bank.domain;
import java.math.BigDecimal;
public class DomainModelDemo {
public static void main(String[] args) {
Account rajesh = new Account("SAV2001", "Rajesh",
new BigDecimal("75000.00"), new BigDecimal("5000.00"));
rajesh.withdraw(new BigDecimal("10000.00"));
System.out.println("After withdrawal: " + rajesh.getBalance());
try {
rajesh.withdraw(new BigDecimal("70000.00"));
} catch (InsufficientBalanceException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
After withdrawal: 65000.00
Rejected: Withdrawal of 70000.00 would leave balance -5000.00, below minimum 5000.00
Why do you separate business rules from infrastructure?
Business rules change for business reasons. Infrastructure changes for technology reasons. Mixing them means a database migration can break your interest calculation, or a Kafka upgrade can change your transfer logic.
Separation gives you:
- Testability. Test business rules with plain unit tests, no database, no Spring context, no test containers.
- Portability. Switch from PostgreSQL to DynamoDB without changing the domain.
- Clarity. A new developer reads the domain package and understands the business without wading through HTTP and SQL code.
- Safety. Business rules are in one place. You do not discover a hidden validation in a controller, a repository, and a stored procedure.
package com.bank.domain;
import java.math.BigDecimal;
// This test runs without any framework, database, or container
public class AccountRulesTest {
public static void main(String[] args) {
Account account = new Account("SAV2001", "Rajesh",
new BigDecimal("10000.00"), new BigDecimal("5000.00"));
// Rule 1: successful withdrawal
account.withdraw(new BigDecimal("3000.00"));
assert account.getBalance().compareTo(new BigDecimal("7000.00")) == 0
: "Balance should be 7000";
// Rule 2: cannot go below minimum balance
boolean rejected = false;
try {
account.withdraw(new BigDecimal("5000.00"));
} catch (InsufficientBalanceException e) {
rejected = true;
}
assert rejected : "Should reject withdrawal below minimum";
// Rule 3: deposit must be positive
boolean invalidDeposit = false;
try {
account.deposit(new BigDecimal("-100.00"));
} catch (IllegalArgumentException e) {
invalidDeposit = true;
}
assert invalidDeposit : "Should reject negative deposit";
System.out.println("All business rule tests passed");
}
}
All business rule tests passed
How does hexagonal architecture enforce this separation?
Hexagonal architecture (also called ports and adapters) places the domain at the center. The domain defines ports, which are interfaces describing what the domain needs from the outside world. Adapters implement those ports using real infrastructure.
The rule: the domain depends on nothing. Everything else depends on the domain.
- Inbound port: an interface that defines a use case the outside world can trigger (e.g.,
TransferUseCase). - Outbound port: an interface that defines what the domain needs from infrastructure (e.g.,
AccountRepository). - Inbound adapter: a controller, CLI, or message listener that calls an inbound port.
- Outbound adapter: a JPA repository, REST client, or Kafka producer that implements an outbound port.
package com.bank.domain.port;
import com.bank.domain.Account;
import java.util.Optional;
// Outbound port: the domain needs to load and save accounts.
// It does not know whether the implementation uses JPA, JDBC, or a file.
public interface AccountRepository {
Optional<Account> findById(String accountId);
void save(Account account);
}
package com.bank.domain.port;
import java.math.BigDecimal;
// Inbound port: defines the transfer use case
public interface TransferUseCase {
void transfer(String fromAccountId, String toAccountId, BigDecimal amount);
}
package com.bank.domain.service;
import com.bank.domain.Account;
import com.bank.domain.port.AccountRepository;
import com.bank.domain.port.TransferUseCase;
import java.math.BigDecimal;
// Domain service implements the use case using only domain objects and ports
public class TransferService implements TransferUseCase {
private final AccountRepository accountRepository;
public TransferService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Override
public void transfer(String fromId, String toId, BigDecimal amount) {
Account from = accountRepository.findById(fromId)
.orElseThrow(() -> new IllegalArgumentException(
"Account not found: " + fromId));
Account to = accountRepository.findById(toId)
.orElseThrow(() -> new IllegalArgumentException(
"Account not found: " + toId));
from.withdraw(amount);
to.deposit(amount);
accountRepository.save(from);
accountRepository.save(to);
}
}
package com.bank.infrastructure;
import com.bank.domain.Account;
import com.bank.domain.port.AccountRepository;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
// Outbound adapter: in-memory implementation for testing
public class InMemoryAccountRepository implements AccountRepository {
private final Map<String, Account> store = new HashMap<>();
public void seed(Account account) {
store.put(account.getAccountId(), account);
}
@Override
public Optional<Account> findById(String accountId) {
return Optional.ofNullable(store.get(accountId));
}
@Override
public void save(Account account) {
store.put(account.getAccountId(), account);
}
}
package com.bank;
import com.bank.domain.Account;
import com.bank.domain.service.TransferService;
import com.bank.infrastructure.InMemoryAccountRepository;
import java.math.BigDecimal;
public class HexagonalDemo {
public static void main(String[] args) {
InMemoryAccountRepository repo = new InMemoryAccountRepository();
repo.seed(new Account("SAV2001", "Rajesh",
new BigDecimal("75000.00"), new BigDecimal("5000.00")));
repo.seed(new Account("SAV3002", "Priya",
new BigDecimal("30000.00"), new BigDecimal("5000.00")));
TransferService service = new TransferService(repo);
service.transfer("SAV2001", "SAV3002", new BigDecimal("25000.00"));
System.out.println("Rajesh: " + repo.findById("SAV2001").get().getBalance());
System.out.println("Priya: " + repo.findById("SAV3002").get().getBalance());
}
}
Rajesh: 50000.00
Priya: 55000.00
What are value objects and why do they matter?
A value object is an immutable class that represents a concept with no identity. Two Money objects with the same amount and currency are equal, regardless of when or where they were created.
Value objects enforce constraints at creation time. An AccountNumber that requires exactly 7 characters prevents invalid data from entering the system.
package com.bank.domain;
import java.math.BigDecimal;
import java.util.Objects;
public record Money(BigDecimal amount, String currency) {
public Money {
if (amount == null || amount.compareTo(BigDecimal.ZERO) < 0) {
throw new IllegalArgumentException(
"Amount must be non-negative, got: " + amount);
}
if (currency == null || currency.isBlank()) {
throw new IllegalArgumentException("Currency is required");
}
}
public Money add(Money other) {
if (!this.currency.equals(other.currency)) {
throw new IllegalArgumentException(
"Cannot add " + this.currency + " and " + other.currency);
}
return new Money(this.amount.add(other.amount), this.currency);
}
public Money subtract(Money other) {
if (!this.currency.equals(other.currency)) {
throw new IllegalArgumentException(
"Cannot subtract " + this.currency + " and " + other.currency);
}
return new Money(this.amount.subtract(other.amount), this.currency);
}
}
package com.bank.domain;
public record AccountNumber(String value) {
public AccountNumber {
if (value == null || !value.matches("[A-Z]{3}\\d{4}")) {
throw new IllegalArgumentException(
"Account number must be 3 uppercase letters + 4 digits, got: " + value);
}
}
}
package com.bank.domain;
import java.math.BigDecimal;
public class ValueObjectDemo {
public static void main(String[] args) {
Money salary = new Money(new BigDecimal("75000.00"), "INR");
Money bonus = new Money(new BigDecimal("15000.00"), "INR");
Money total = salary.add(bonus);
System.out.println("Total: " + total.amount() + " " + total.currency());
AccountNumber acc = new AccountNumber("SAV2001");
System.out.println("Account: " + acc.value());
try {
new AccountNumber("invalid");
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
try {
Money inr = new Money(new BigDecimal("100.00"), "INR");
Money usd = new Money(new BigDecimal("50.00"), "USD");
inr.add(usd);
} catch (IllegalArgumentException e) {
System.out.println("Currency mismatch: " + e.getMessage());
}
}
}
Total: 90000.00 INR
Account: SAV2001
Rejected: Account number must be 3 uppercase letters + 4 digits, got: invalid
Currency mismatch: Cannot add INR and USD
How is a rich domain model different from an anemic domain model?
| Aspect | Rich domain model | Anemic domain model |
|---|---|---|
| Entity behavior | Entities have methods that enforce rules | Entities are data holders (getters/setters only) |
| Where rules live | In the entity class | In a separate service class |
| Encapsulation | Strong: state is protected | Weak: state is exposed via setters |
| Testing | Test the entity directly | Test the service, mock the entity |
| Example | account.withdraw(amount) validates minimum balance | transferService.withdraw(account, amount) validates externally |
| Advocated by | Domain-Driven Design | Transaction Script pattern |
package com.bank.domain;
import java.math.BigDecimal;
// ANEMIC: entity is just data, no business logic
class AnemicAccount {
private String accountId;
private BigDecimal balance;
public String getAccountId() { return accountId; }
public void setAccountId(String id) { this.accountId = id; }
public BigDecimal getBalance() { return balance; }
public void setBalance(BigDecimal b) { this.balance = b; }
}
class AnemicTransferService {
// Rules scattered in service, not in the entity
void withdraw(AnemicAccount account, BigDecimal amount) {
BigDecimal newBalance = account.getBalance().subtract(amount);
if (newBalance.compareTo(new BigDecimal("5000")) < 0) {
throw new RuntimeException("Below minimum");
}
account.setBalance(newBalance);
}
}
package com.bank.domain;
import java.math.BigDecimal;
// RICH: entity enforces its own rules
// (Already shown above: Account.withdraw validates minimum balance)
public class RichVsAnemicDemo {
public static void main(String[] args) {
// Rich model: account protects its own invariants
Account rich = new Account("SAV2001", "Rajesh",
new BigDecimal("75000.00"), new BigDecimal("5000.00"));
rich.withdraw(new BigDecimal("10000.00"));
System.out.println("Rich model balance: " + rich.getBalance());
// Anemic model: service does the validation
AnemicAccount anemic = new AnemicAccount();
anemic.setAccountId("SAV2001");
anemic.setBalance(new BigDecimal("75000.00"));
new AnemicTransferService().withdraw(anemic, new BigDecimal("10000.00"));
System.out.println("Anemic model balance: " + anemic.getBalance());
}
}
Rich model balance: 65000.00
Anemic model balance: 65000.00
What are domain events?
A domain event is a record of something that happened in the domain. When Rajesh transfers money, the domain produces a TransferCompleted event. The notification service and audit service consume it. The domain does not know about emails or audit tables.
package com.bank.domain.event;
import java.math.BigDecimal;
import java.time.Instant;
public record TransferCompleted(
String transactionId,
String fromAccount,
String toAccount,
BigDecimal amount,
Instant occurredAt
) {}
package com.bank.domain.event;
public interface DomainEventPublisher {
void publish(Object event);
}
package com.bank.domain.event;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
public class DomainEventDemo {
static List<Object> publishedEvents = new ArrayList<>();
public static void main(String[] args) {
DomainEventPublisher publisher = publishedEvents::add;
// Domain produces the event
TransferCompleted event = new TransferCompleted(
"TXN-5001", "SAV2001", "SAV3002",
new BigDecimal("25000.00"), Instant.now());
publisher.publish(event);
// Infrastructure adapters consume it
for (Object e : publishedEvents) {
if (e instanceof TransferCompleted tc) {
System.out.println("Notification: Transfer of "
+ tc.amount() + " from " + tc.fromAccount()
+ " to " + tc.toAccount());
System.out.println("Audit: Logged transaction " + tc.transactionId());
}
}
}
}
Notification: Transfer of 25000.00 from SAV2001 to SAV3002
Audit: Logged transaction TXN-5001
What are common mistakes in domain modeling?
Mistake 1: Putting business rules in the controller
Wrong: the controller validates and processes the transfer.
package com.bank.web;
import java.math.BigDecimal;
// WRONG: Business logic in the controller
public class TransferControllerBad {
public String transfer(String from, String to, BigDecimal amount) {
// Business rule leaked into HTTP layer
if (amount.compareTo(new BigDecimal("1000000")) > 0) {
return "ERROR: Transfer exceeds 10 lakh limit";
}
// Direct database call from controller
System.out.println("UPDATE accounts SET balance = balance - " + amount
+ " WHERE id = '" + from + "'");
return "OK";
}
public static void main(String[] args) {
String result = new TransferControllerBad()
.transfer("SAV2001", "SAV3002", new BigDecimal("1500000"));
System.out.println(result);
}
}
ERROR: Transfer exceeds 10 lakh limit
Correct: the controller delegates to a domain service. The domain service uses domain objects.
package com.bank.web;
import com.bank.domain.service.TransferService;
import com.bank.infrastructure.InMemoryAccountRepository;
import com.bank.domain.Account;
import java.math.BigDecimal;
// CORRECT: Controller is thin, delegates to domain
public class TransferControllerGood {
private final TransferService transferService;
public TransferControllerGood(TransferService transferService) {
this.transferService = transferService;
}
public String handleTransfer(String from, String to, BigDecimal amount) {
try {
transferService.transfer(from, to, amount);
return "Transfer successful";
} catch (Exception e) {
return "Transfer failed: " + e.getMessage();
}
}
public static void main(String[] args) {
InMemoryAccountRepository repo = new InMemoryAccountRepository();
repo.seed(new Account("SAV2001", "Rajesh",
new BigDecimal("75000.00"), new BigDecimal("5000.00")));
repo.seed(new Account("SAV3002", "Priya",
new BigDecimal("30000.00"), new BigDecimal("5000.00")));
TransferControllerGood controller = new TransferControllerGood(
new TransferService(repo));
System.out.println(controller.handleTransfer(
"SAV2001", "SAV3002", new BigDecimal("25000.00")));
}
}
Transfer successful
What is the project structure for hexagonal architecture?
A typical banking project separates domain, application, and infrastructure into distinct packages or modules.
com.bank/
domain/
Account.java # Entity with business rules
InsufficientBalanceException.java
Money.java # Value object
AccountNumber.java # Value object
event/
TransferCompleted.java # Domain event
DomainEventPublisher.java # Port interface
port/
AccountRepository.java # Outbound port
TransferUseCase.java # Inbound port
service/
TransferService.java # Domain service
infrastructure/
persistence/
JpaAccountRepository.java # Outbound adapter (JPA)
InMemoryAccountRepository.java
messaging/
KafkaEventPublisher.java # Outbound adapter (Kafka)
web/
TransferController.java # Inbound adapter (HTTP)
What should a senior engineer know?
- Aggregate roots. In Domain-Driven Design, an aggregate is a cluster of entities and value objects with a single root entity. External code accesses the cluster only through the root. In banking, an Account is the aggregate root for its Transactions. You never modify a Transaction without going through the Account.
- Bounded contexts. Different teams may model the same concept differently. The Account in the Lending context has loan details. The Account in the Payments context has transaction history. Each bounded context has its own domain model, and they communicate through events or APIs.
- Anti-corruption layer. When integrating with a legacy system or third-party API, build a translation layer that converts external data formats into your domain objects. This prevents external models from polluting your domain.
- CQRS with domain modeling. Separate the write model (rich domain entities) from the read model (flat projections optimized for queries). The write side enforces rules. The read side serves fast queries without loading full aggregates.
- Testing strategy. Unit-test domain entities and value objects with no mocks. Integration-test domain services with fake repositories. End-to-end test adapters with test containers.
What are common interview follow-up questions?
- What is the difference between an entity and a value object?
- How do you handle cross-aggregate transactions?
- What is the Specification pattern and when do you use it?
- How do you version domain events for backward compatibility?
- When is an anemic domain model acceptable?
Visual Overview
Hexagonal Architecture
========================
Inbound Adapters Domain Core Outbound Adapters
───────────────── ───────────────────── ─────────────────────
│ REST Controller│ │ │ │ JPA Repository │
│ (Spring MVC) │───>│ TransferService │───>│ (PostgreSQL) │
└────────────────┘ │ │ └──────────────────┘
│ Account (entity) │
┌────────────────┐ │ Money (value obj) │ ┌──────────────────┐
│ Kafka Listener │───>│ AccountNumber │───>│ Kafka Producer │
│ (Spring Kafka) │ │ (value obj) │ │ (events) │
└────────────────┘ │ │ └──────────────────┘
│ Ports: │
┌────────────────┐ │ - TransferUseCase │ ┌──────────────────┐
│ CLI / Batch │───>│ - AccountRepo │───>│ SMTP Adapter │
│ (scheduled) │ │ - EventPublisher │ │ (notifications) │
└────────────────┘ └───────────────────┘ └──────────────────┘
Rule: Arrows point INWARD. Domain depends on NOTHING external.
Adapters depend on the domain. Never the reverse.
Dependency Direction
=====================
Controller ──> UseCase (port) <── DomainService ──> Repository (port) <── JpaAdapter
│ │
│ Domain layer (no imports from Spring/JPA) │
└────────────── Infrastructure layer (imports everything) ──────────────┘
Key Takeaway
Domain modeling starts with understanding the business. At National Bank of India, an account has a minimum balance rule, a transfer has a daily limit, and a loan has an EMI formula. These rules do not come from Spring or PostgreSQL. They come from the bank's policies. Domain modeling puts those rules into Java classes that compile and run without any framework.
The key insight is dependency direction. The domain layer defines interfaces (ports) for what it needs: a place to load accounts, a way to publish events. Infrastructure adapters implement those interfaces using JPA, Kafka, or REST. The domain never imports a framework class. This means you can test every business rule with plain unit tests: create an Account, call withdraw, and assert the result. No database, no Spring context, no test containers.
Value objects like Money and AccountNumber enforce constraints at creation time. You cannot create a Money with a negative amount or an AccountNumber with the wrong format. This pushes validation to the boundary and keeps the interior clean. Domain events like TransferCompleted communicate what happened without coupling the domain to email services or audit tables.
The difference between a rich model and an anemic model is where the rules live. In a rich model, the Account class enforces its minimum balance. In an anemic model, a separate service does the checking while the Account is just a data bag with getters and setters. Rich models are harder to build but much easier to trust.
One sentence to remember: the domain model contains the business rules, the infrastructure implements the technology, and the dependency arrow always points inward toward the domain.
---