Anemic domain model and Rich Model

This article is assited by ChatGPT ai and Midjourney ai

(KJH) Kuan-Jung, Huang
2 min readDec 6, 2022

Anemic domaim model

An anemic domain model is a type of software design in which the domain model does not contain any business logic. This type of model is often criticized because it violates the principles of object-oriented design, which state that an object should contain both data and behavior.

Here is an example of a simple domain model that represents a Person:

class Person {
String name;
String email;
String address;
String phone;

public Person(String name, String email, String address, String phone) {
this.name = name;
this.email = email;
this.address = address;
this.phone = phone;
}

public String getName() {
return this.name;
}

public String getEmail() {
return this.email;
}

public String getAddress() {
return this.address;
}

public String getPhone() {
return this.phone;
}
}

This is an example of an anemic domain model because it only contains data, and no business logic. It does not contain any methods that perform actions on the data, such as calculating a person’s age, formatting their phone number, or validating their email address.

Rich doamin model

A rich domain model is one that contains both data and behavior. Here is an example of a Person class that is a rich domain model:

class Person {
String name;
String email;
String address;
String phone;

public Person(String name, String email, String address, String phone) {
this.name = name;
this.email = email;
this.address = address;
this.phone = phone;
}

public String getName() {
return this.name;
}

public String getEmail() {
return this.email;
}

public String getAddress() {
return this.address;
}

public String getPhone() {
return this.phone;
}

public void setName(String name) {
this.name = name;
}

public void setEmail(String email) {
if (isValidEmail(email)) {
this.email = email;
}
}

public void setAddress(String address) {
this.address = address;
}

public void setPhone(String phone) {
if (isValidPhone(phone)) {
this.phone = phone;
}
}

private boolean isValidEmail(String email) {
// Implement email validation logic here
}

private boolean isValidPhone(String phone) {
// Implement phone validation logic here
}
}

This Person class is a rich domain model because it contains both data (instance variables and getter methods) and behavior (methods that perform actions on the data, such as setName(), setEmail(), setAddress(), and setPhone()). You can encapsulte more customize domain logic onto this Pereson class to represent the object behavior.

--

--

(KJH) Kuan-Jung, Huang
(KJH) Kuan-Jung, Huang

Written by (KJH) Kuan-Jung, Huang

CTO at Metablox.co, Founder of AI Users Community in Taiwan

No responses yet