Book › DDD

Modeling a domain and its layers in Kotlin

Model entities and immutable values in Kotlin, then apply dependency inversion across the presentation, application, domain, and infrastructure layers.

Modeling a domain and its layers in Kotlin

In my notes on Chapters 1 and 2 of Choi Beom-gyun’s Getting Started with Domain-Driven Development, I use a shop to separate entity behavior from immutable values and keep infrastructure dependencies out of the rules that drive an order.

The examples use Kotlin 1.9, Java 21, Spring Boot 3.x, and Spring Data JPA with Hibernate 6.

Start with the terms the business uses

A domain is the problem area a system serves. An online shop has several subdomains, including catalog, membership, orders, payments, and shipping. Each has its own reasons to change. If they all share a single service, a change to shipping rules can ripple through unrelated checkout code.

I start with a small conceptual model I can discuss with stakeholders. It identifies the decisions the system needs to make and names the facts those decisions depend on. As I implement the rules and learn where the model is incomplete, I revise the model and code together. The implementation model grows out of those iterations.

Ubiquitous language keeps that conversation grounded. If the team says an order is waiting for payment, STEP_1 forces readers to translate a workflow number. PAYMENT_WAITING conveys the state the team discusses. PREPARING and cancel() do the same for the next business decision. When a test fails, the name should help a reader recognize the rule at stake.

Give entities behavior and values equality

An entity has an identity that survives state changes. An order is still the same order after its shipping address changes. A value object describes a value at a point in time. Two addresses with the same components are interchangeable wherever the address is used.

ConcernEntityValue object
EqualityStable identifier such as OrderNoValues of its attributes
LifetimeChanges state while retaining identityReplaced when a value changes
Kotlin representationA class with methods that express behaviorA data class with immutable properties where appropriate
ExamplesOrder, Member, ProductMoney, Address, ShippingInfo, Receiver

If two objects hold the same mutable Address, a change through one reference can alter both. The example values hold val properties and construct replacements. The Money operators return fresh values. The constructor rejects negative amounts for this shop’s model. A model that uses credits or negative balances would need to spell out its own rule.

1
2
3
4
5
6
7
8
9
10
11
// com/example/shop/common/model/Money.kt
package com.example.shop.common.model

data class Money(val value: Int) {
    init {
        require(value >= 0) { "Money cannot be negative: $value" }
    }

    operator fun plus(other: Money): Money = Money(value + other.value)
    operator fun times(multiplier: Int): Money = Money(value * multiplier)
}

Calling cancel() or changeShippingInfo() asks the order to enforce its shipping rule. If callers can assign order.state directly, each of them needs to remember the validation. Tests can exercise the rule without starting Spring. Cancellation ought to work while the order is waiting for payment or preparing, and a shipped order should reject cancellation and an address change.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// com/example/shop/order/domain/OrderModels.kt
package com.example.shop.order.domain

import com.example.shop.common.model.Money
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
import jakarta.persistence.Embedded
import jakarta.persistence.EmbeddedId
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.Table
import java.io.Serializable

@Embeddable
data class OrderNo(
    @Column(name = "order_number")
    val number: String
) : Serializable

enum class OrderState {
    PAYMENT_WAITING, PREPARING, SHIPPED, DELIVERING, DELIVERY_COMPLETED, CANCELED
}

@Embeddable
data class Receiver(
    @Column(name = "receiver_name") val name: String,
    @Column(name = "receiver_phone") val phone: String
)

@Embeddable
data class Address(
    @Column(name = "shipping_zip_code") val zipCode: String,
    @Column(name = "shipping_addr1") val address1: String,
    @Column(name = "shipping_addr2") val address2: String
)

@Embeddable
data class ShippingInfo(
    @Embedded val receiver: Receiver,
    @Embedded val address: Address,
    @Column(name = "shipping_message") val message: String
)

@Entity
@Table(name = "purchase_order")
class Order(
    @EmbeddedId
    val number: OrderNo,
    shippingInfo: ShippingInfo,
    totalAmounts: Money
) {
    @Embedded
    var shippingInfo: ShippingInfo = shippingInfo
        protected set

    @Column(name = "total_amounts")
    var totalAmounts: Money = totalAmounts
        protected set

    @Enumerated(EnumType.STRING)
    @Column(name = "state")
    var state: OrderState = OrderState.PAYMENT_WAITING
        protected set

    fun changeShippingInfo(newShippingInfo: ShippingInfo) {
        verifyNotYetShipped()
        this.shippingInfo = newShippingInfo
    }

    fun cancel() {
        verifyNotYetShipped()
        this.state = OrderState.CANCELED
    }

    fun verifyNotYetShipped() {
        check(state == OrderState.PAYMENT_WAITING || state == OrderState.PREPARING) {
            "Cannot change or cancel the order in its current state: $state"
        }
    }
}

When several objects must change together, I put their invariants behind an aggregate root.

Point infrastructure dependencies inward

The four layers divide the work by concern. Presentation translates an HTTP request into input the application can use. Application coordinates the transaction and use case. Domain owns the rules. Infrastructure implements database access and external integrations.

The dependency inversion principle (DIP) lets the domain define a dependency in its own vocabulary. Here, CalculateDiscountService needs a RuleDiscounter. That interface belongs to the domain. DroolsRuleDiscounter adapts the rule engine to it.

flowchart TD
    UI["Presentation (OrderController)"] --> APP["Application (CalculateDiscountService)"]
    APP -->|"Uses interface"| PORT["Domain (RuleDiscounter)"]
    APP -->|"Delegates rules"| DOM["Domain (Order / Money)"]
    INFRA["Infrastructure (DroolsRuleDiscounter)"] -.->|"Implements"| PORT
1
2
3
4
5
6
7
8
// com/example/shop/order/domain/RuleDiscounter.kt
package com.example.shop.order.domain

import com.example.shop.common.model.Money

interface RuleDiscounter {
    fun applyRules(customerGrade: String, orderAmount: Money): Money
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// com/example/shop/order/application/CalculateDiscountService.kt
package com.example.shop.order.application

import com.example.shop.common.model.Money
import com.example.shop.order.domain.RuleDiscounter
import org.springframework.stereotype.Service

@Service
class CalculateDiscountService(
    private val ruleDiscounter: RuleDiscounter
) {
    fun calculateDiscount(customerGrade: String, orderAmount: Money): Money {
        return ruleDiscounter.applyRules(customerGrade, orderAmount)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// com/example/shop/order/infra/DroolsRuleDiscounter.kt
package com.example.shop.order.infra

import com.example.shop.common.model.Money
import com.example.shop.order.domain.RuleDiscounter
import org.springframework.stereotype.Component

@Component
class DroolsRuleDiscounter : RuleDiscounter {
    override fun applyRules(customerGrade: String, orderAmount: Money): Money {
        val discountRate = if (customerGrade == "VIP") 10 else 0
        return Money(orderAmount.value * discountRate / 100)
    }
}

At compile time, the domain and application have no import of DroolsRuleDiscounter. At runtime, Spring’s DefaultListableBeanFactory registers the infrastructure component and resolves the constructor parameter by type. Replacing the rule engine affects the adapter and its wiring. The use case continues to call the same interface.

I group these packages under a feature such as com.example.shop.order so the service, model, and adapter are easy to find together. A package boundary also makes model ownership apparent before a separate module or deployment is necessary.

Watch for equality and proxy surprises

Kotlin data class generates equals(), hashCode(), toString(), and copy() from the primary constructor properties. Those defaults fit small immutable values. An entity can have mutable state, lazy associations, and a persistence provider proxy. Comparing fields can trigger SQL or make objects disappear from a hash-based collection when a field changes. toString() can traverse an association that leads back to the entity. A final type can also prevent Hibernate from using a subclass proxy.

Use identity for entity equality and check how your JPA provider proxies the type. If the identifier is assigned on insert, account for the transient state before using it as a hash key.

I introduce an interface when it isolates a significant dependency, such as a database, payment provider, or rules engine. An interface for every concrete class adds a second place to look even where there is no meaningful boundary.

Checks before extending the model

  • Name each state and action in terms the business already uses.
  • Put rules that must hold after each change behind behavior methods.
  • Keep value equality stable and entity state changes explicit.
  • Test the rules without infrastructure, then test how the adapter is wired.

The original Java samples are maintained alongside the book.

Contribute to madvirus/ddd-start2 development by creating an account on GitHub.
This post is licensed under CC BY 4.0 by the author.