class OrderService {
CartDto addItem(cartId, productId) {
var cart = cartRichDao.findById(cardId)
var prod = productRichDao.findById(productId)
// service layer not allow mutate Cart entity directly, delegate to rich DAO
var updatedCart = cartRichDao.addItem(cart, prod, clock.instant())
return updatedCart.toDto()
}
}
class CartRichDao {
Cart addItem(cart, product, instant) {
var updated = cart.addItem(product, instant)
var itemChanged = cart.diff(updated)
db.execute("update cart set updatedAt = ? where id = ? ...", updated...)
//pseudo code, insert or update depends on itemChanged
db.execute("update item set qty = qty + 1...", itemChanged...)
//domain event should be in service layer, but this is demo code...
publisher.publishEvent(itemChanged)
return updated
}
}
//immutable entity
record class Cart(long id, List<Item> items, Instant updatedAt) {
Cart addItem(product, instant) {
// if item exist
// qty+1
// else
// add new item
return new Cart(this.id, copiedNewItems, instant)
}
ItemChanged diff(cart) {
// compute items diff
// ...
}
}
Last active
July 6, 2026 18:35
-
-
Save ingramchen/3934cdbd06a7d9cca597c573a5abd781 to your computer and use it in GitHub Desktop.
rich dao
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment