Dec 2, 2026
Domain Modeling Walkthrough with an Extremely Simple Scenario
Starting from the simplest Key-Value object, a step-by-step domain modeling walkthrough: value object abstraction, persistence modeling, grouping and association, tree structures, JSON deserialization, and value parsing — ending in responsibility and service interface design.
1. Background
Recently my company has been preparing to develop business components, and I was also getting ready to give a technical talk on DDD Theory and Practice. While designing the generic business component solution, I came across a case that is particularly easy to understand and easy to explain. I’m recording it here to share it with you all.
2. Key-Value Objects
2.1 The Basic KV Model
Many projects use KV objects, but they are used in different ways. The tables in SQL, strictly speaking, are a K-V store — more precisely a K-VList. The purest KV is a Map, such as Map<K,V>. Looking at the basic KV model, K means “I know who you are,” and V means “I know what you are.” This model is also called the key-value pair model: K is the key, V is the value. Many low-level frameworks use the key-value model to simplify operations on their data models. It is the purest model abstracted from reality, and also the simplest one.
2.2 Usage Scenarios for KV Objects
There are many scenarios for using KV objects. Here are a few examples:
- The K-VList model of a MySQL column
- Enums: models with two to a handful of KV fields
- The Map data model
- Uniqueness models: once the rules for a key’s value are defined, the uniqueness model is determined
- Business configuration objects extended from KV, such as a three-element model (
id-k-v,k-v-desc), or several database records backed by configuration - Dictionaries: also a typical KV object model, though its professional name is inverted index, a V-K variant of KV
- Generic applications of KV objects, such as
Key<K>andValue<V>
2.3 Applying KV Objects in Domain Modeling
In DDD, domain objects come in two kinds: entities and value objects. The metadata inside an entity is really a series of KV collections. But KV objects themselves do not express much business behavior or many business attributes. In practice, though, KV is extremely widely used as a value object and adapts well to that role. So personally I think KV objects can be seen as a kind of abstraction of value objects.
2.4 Generic Java Classes for KV Objects
First, let’s look at a generic class built on a KV object:
package com.coderman.utils.kvpair;
import java.util.Objects;
/**
* description: KVPair <br>
* date: 2020/7/18 0:29 <br>
* author: coderman <br>
* version: 1.0 <br>
* k-v key-value pair object
*/
public class KVPair<K, V> {
public KVPair(){
}
public KVPair(K k, V v){
this.k = k;
this.v = v;
}
protected K k;
protected V v;
public K getK() {
return k;
}
public void setK(K k) {
this.k = k;
}
public V getV() {
return v;
}
public void setV(V v) {
this.v = v;
}
// A static method for building K-V instances
public static <K, V> KVPair<K, V> build(K k, V v) {
return new KVPair<>(k, v);
}
// The ability to tell whether two K-V objects are identical
@Override
public boolean equals(Object o) {
if (this == o){
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
KVPair<?, ?> kvPair = (KVPair<?, ?>) o;
return Objects.equals(k, kvPair.k) &&
Objects.equals(v, kvPair.v);
}
@Override
public int hashCode() {
return Objects.hash(k, v);
}
}
Second, the K-V-P extension:
package com.coderman.utils.kvpair;
import java.util.Objects;
/**
* description: KVParentPair <br>
* date: 2020/9/6 16:09 <br>
* author: coderman <br>
* version: 1.0 <br>
* a triple with a parent-child relationship
*/
public class KVParentPair<K, V, P> extends KVPair<K, V> {
private P p;
public KVParentPair(){}
public KVParentPair(K k, V v ,P p){
super(k,v);
this.p = p;
}
public P getP() {
return p;
}
public void setP(P p) {
this.p = p;
}
public static <K, V> KVPair<K, V> build(K k, V v) {
return new KVPair<>(k, v);
}
@Override
public boolean equals(Object o) {
if (this == o){
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
KVParentPair<?, ?, ?> kvParentPair = (KVParentPair<?, ?, ?>) o;
return Objects.equals(kvParentPair.k, super.k) &&
Objects.equals(kvParentPair.v, super.v) && Objects.equals(kvParentPair.p, this.p);
}
@Override
public int hashCode() {
return Objects.hash(super.k, super.v, p);
}
}
3. Business Scenario Modeling for Key-Value Objects
Let’s do a round of business modeling for key-value objects, simulate a few real-world scenarios, and try to arrive at a fairly generic KV business object and service class.
3.1 As a Value Object Inside Other Objects (K-V only)
If the KVPair object is used as a value object inside other objects, we can draw a UML class diagram for it and get the basic KVPair business model:
We have given the KV object a simple first pass: right now two methods express its initial capabilities. So what happens when we run into the situations below, and how do we extend from this object? From a domain modeling perspective, let’s see how to build richer capabilities on top of it.
3.2 When K-V Has Meaning in Data (id-k-v)
Now we need to store these KV objects in a database, which means read and write persistence. So we need to change the KV object above and add a service class to operate on it. We will not add fields like creator or creation time here; the point is to highlight the key-value pair’s business capability.
3.3 Supporting Grouping of K-V Pairs
Now suppose the boss asks us to extend the use of KV objects in the business. There are two scenarios.
1. Grouping by the k attribute
For example, we may need to group keys by a business scenario, or scatter one business object across several storage groups. We need to extend KVPairBO further, into the shape below:
@startuml
class "Key-Value Pair" as KVPairBO<K,V> {
id:Long id;
K k;
V v;
groupKey:String groupKey;
//get/set/construct
+build kv instance:static <K, V> KVPair<K, V> build(K k, V v)
+build kv instance:static <K, V> KVPair<K, V> build(K k, V v,String groupKey)
+check equality:boolean equals(Object o)
}
class "Business Operation Service for Key-Value Pairs" as KVPairService{
query all:List<KVPairBO> getAll()
get by id:KVPairBO getById(Long id)
insert and return:KVPairBO insert(KVPairBO kVPairBO)
exists by key:boolean containsKey(String key)
exists by key and groupKey:boolean containsKey(String key,String groupKey)
query all by groupKey:List<KVPairBO> getAllList(String groupKey)
query map by groupKey:Map<String,KVPairBO> getAllMap(String groupKey)
}
@enduml
2. K-V as a collection attached to an external record
From the first case we know that some keys are similar, so we added an attribute for grouping, and KVPairService now exposes a few more methods. Next, suppose KV pairs live in the database as extension fields of a table or a business object — product extension properties, for example. Using groupKey for this is clearly not a good fit: if one object needs several groups of KV structures, a single field is not enough. Let’s see whether adding two fields solves the problem:
3.4 Supporting Parent-Child Relationships Between K-V Pairs
We have now extended K-V relationships along two dimensions in 3.3. Let’s see how to build a tree structure — an organization tree, say — out of KVPair. It is not impossible to use groupKey, relationKey, and relationId for this, but the code would get complicated and would fail to express the meaning of a tree. Let’s look at how the class diagram below solves that:
3.5 Supporting Complex Business Objects as Values (JSON)
We have mostly finished expanding the key dimension; now let’s look at the value. Suppose some business rules or configuration objects also want to be managed through the KVPair structure, with the one difference that the value is a JSON string that must be serialized and deserialized. A string value supports JSON naturally, but how do we support serialization and deserialization on top of that? Let’s see how to do it without adding a field, in the class diagram below:
As you can see, adding a single method to KVPairBO handles the requirement. Serialization just goes through the build method, and the generic types remain K and String. To fully support this case, you could add another generic parameter representing the object to deserialize into, so the object itself has complete control over JSON serialization and deserialization.
3.6 Parsing the Value into Specific Data Such as Count or Size
At this point you may find this interesting, or you may think it is nothing special. Let’s play with it a bit more. Suppose we know roughly what the value contains or how it is formatted. Generics alone can no longer fully satisfy how KV is defined across all these scenarios, and adding generic parameters gets extremely complex. We can go one step further with value parsing: beyond parsing and serializing JSON strings, we can escape the constraints of the KV generics and pull out concrete values — a JSON array, for instance, or a plain concatenated string. We can keep enhancing the object, as shown below:
3.7 The Value Type Problem
By now the KV object is starting to look unrecognizable. One reason it got so complex is that both K and V are generic: when V’s structure cannot be constrained by generics, the definition of V and the actual ways its value is used slip out of control. A simple fix is to add a String varType field to KVPairBO that records the approximate type of V. I will skip the full UML diagram here and leave it to your imagination.
3.8 Reversing KV
If you are already a little amazed by this point, here is one more small extension. Suppose we have used this data structure to implement a few business features. Now comes a requirement to import data: the Excel file contains values, and we need to match each to its key. But what is actually held in memory may be KV pairs or a Map<K,V>. How do we find K quickly without iterating over everything?
3.9 Sorting by Key
Following on from the UML class diagrams above, one more extension: when a List<KV> needs to be sorted by K or by value, KVPairBO needs to implement an interface that supports object comparison. I won’t go deeper into that here.
4. Summary
Following domain modeling thinking, we started from the simplest KV object and worked through a lot of scenarios. This is a miniature picture of why an engineering module grows until it becomes uncontrollable. Even the structure we have reached here may be hard to control in real use, partly because the problem sits not only at the BO object level but also has to do with persistence. On top of that, packing all of these scenarios into one class and one business model is clearly problematic: it violates the single responsibility principle in Java code design.
KVPairBO itself is not too bad, but KVPairService is where I deliberately used DDD’s standalone-class style to show you the damage that not defining interfaces can cause.
Now that we know where the problem is, we can address it directly: define a few service interfaces and give each scenario its own implementation. In other words, split KVPairService up, let each implementation own one responsibility, and leave KVPairService to handle routing or common logic at most.
By this point the case is no longer simple. If you also need to recognize the type of the value, the amount of code grows even further.
Comments
Comments are powered by GitHub Discussions. Sign in with GitHub to join the discussion.