{{announcement.body}}
{{announcement.title}}

Anemic Domain Model in Typical Spring Projects (Part 2)

DZone 's Guide to

Anemic Domain Model in Typical Spring Projects (Part 2)

Continue learning about the anemic domain model, its benefits and drawbacks, and how to apply it to enterprise Spring projects.

· Java Zone ·
Free Resource

(Continued from Part 1)

Rich Domain Model Extreme could be an alternative, but in my opinion, you shouldn’t inject infrastructure classes to domain classes. Such code will quickly become unsupported and hell for testing, because every programmer has their own style of coding and in practice, this often violates conventions and good practices. Therefore, experience is tremendously important in this case. That is why we have to find some balance in anemic and rich models. In order to get a deeper knowledge of this topic, I would recommend reading this article.

What is important for us is that the author recommends sticking to three rules:

  1. Operations/methods added to a Domain Object should mutate ONLY in the current JVM memory state of that object, and NOT any external state (i.e. state in a database).

  2. Operations in the orchestrating objects (Manager/Service) should NOT break if the state of a Domain Object changes. This can be achieved if they always ask domain objects for answers to domain questions instead of trying to figure out the answers themselves.

  3. Operations on the Domain Object should ONLY use the current JVM memory state of the object.

Now we can see the depth of the problem. Both approaches have serious flaws. It is worth a try to make a hybrid of two models. On the one hand, it will be an enhanced anemic model, but on the other hand, we should beware that it could inherit the drawbacks of both models. So in our services, we will place only methods that use infrastructure, and in the model, we place business logic that operates with fields of the class.

In that case, the domain classes will look like this:

Java
 




x
32


1
@Data
2
@Entity
3
@Table(name = "user", schema = "expenses")
4
public class UserEntity {
5
 
          
6
    @Id
7
    @GeneratedValue(strategy = GenerationType.IDENTITY)
8
    @Column(name = "id")
9
    private Integer id;
10
 
          
11
    @Column(name = "email")
12
    private String email;
13
    ...
14
 
          
15
    @OneToMany(mappedBy="user")
16
    private List<ExpenseEntity> expenses;
17
 
          
18
    ...
19
 
          
20
    public Integer calculateAllExpensesPrice() {
21
        return expenses.stream()
22
                .mapToInt(expenseEntity -> expenseEntity.getPrice() * getUserDiscount(expenseEntity))
23
                .sum();
24
    }
25
    
26
    public List<ExpenseTypeDictEntity> getExpenseTypes() {
27
        return expenses.stream()
28
                .flatMap(expenseEntity -> expenseEntity.getExpenseTypeDict().stream())
29
                .collect(Collectors.toList());
30
    }
31
 
          
32
}



It is easy to cover a class like this with tests. UserService will use the model's methods. Just insert a few mocks in the service and an integration test is ready!

One more thing about rules 1 and 3. In my opinion, there could be an exception. If we use lazy loading inside the model and it works with satisfactory performance, we can unstick. Moreover, there are ways to efficiently use this approach, for example the @Fetch annotation:

Java
 




xxxxxxxxxx
1
16


1
@Data
2
@Entity
3
@Table(name = "expense", schema = "expenses")
4
public class ExpenseEntity {
5
    
6
    // other fields
7
    ...
8
    
9
    @ManyToMany(fetch = FetchType.LAZY)
10
    @JoinTable(name = "expense_to_expense_type_dict", schema = "expenses",
11
            joinColumns = @JoinColumn(name = "expense_id"),
12
            inverseJoinColumns = @JoinColumn(name = "expense_type_id"))
13
    @Fetch(FetchMode.SUBSELECT) // when we call one element of the list - hibernate will quiry whole list instead.
14
    private List<ExpenseTypeDictEntity> expenseTypeDict;
15
 
          
16
}



In addition to all of the above, it should be noted that even if all best practices are followed, refactoring sometimes CANNOT be done due to external constraints. First and foremost, a database limits us in many ways. We cannot just move fields from one object to another or change them because we have to make appropriate changes in the DB, which could be impossible. Sometimes other projects use the same DB directly, which is not a very good idea. Do you remember that we should use interfaces to work with classes? The same rule applies to other services. 

As already mentioned, the use of an anemic domain model leads to the impossibility or reduction of the efficiency of many refactoring techniques and design patterns.

For example, Builder has great use in the model. You can easily move long methods of model objects initialization into the objects themselves. The service will no longer have methods like initExpenseEntity (expenseDTO) with 20 lines of setParameter (value)… We can add methods that initialize fields with default values, accept DTOs or other objects, etc. The main thing is that this code will not be in the service now.

Instead of:

Java
 




xxxxxxxxxx
1
14


1
private void initExpenseEntity(ExpenseEntity expenseEntity, ExpenseDTO expenseDTO) {
2
    UserEntity userEntity = authenticationBO.getLoggedUser();
3
 
          
4
    expenseEntity.setUser(userEntity);
5
    expenseEntity.setPrice(expenseDTO.getPrice());
6
    expenseEntity.setComment(expenseDTO.getComment());
7
    if (expenseDTO.getDate() != null)
8
        expenseEntity.setDate(expenseDTO.getDate());
9
    else
10
        expenseEntity.setDate(LocalDateTime.now());
11
    initExpenseTypes(expenseEntity, expenseDTO.getTypes());
12
    
13
    ...
14
}



Will be:

Java
 




xxxxxxxxxx
1
67


 
1
@Data
2
@Entity
3
@Table(name = "expense", schema = "expenses")
4
public class ExpenseEntity {
5
 
          
6
    @Id
7
    @GeneratedValue(strategy = GenerationType.IDENTITY)
8
    @Column(name = "id")
9
    private Integer id;
10
 
          
11
    @Column(name = "price")
12
    private Integer price;
13
 
          
14
    @Column(name = "comment")
15
    private String comment;
16
 
          
17
    @Column(name = "date")
18
    private LocalDateTime date;
19
 
          
20
    @ManyToOne(fetch = FetchType.LAZY)
21
    @JoinColumn(name = "user_id")
22
    private UserEntity user;
23
 
          
24
    @ManyToMany(fetch = FetchType.LAZY)
25
    @JoinTable(name = "expense_to_expense_type_dict", schema = "expenses",
26
            joinColumns = @JoinColumn(name = "expense_id"),
27
            inverseJoinColumns = @JoinColumn(name = "expense_type_id"))
28
    @Fetch(FetchMode.SUBSELECT)
29
    private List<ExpenseTypeDictEntity> expenseTypeDict;
30
 
          
31
 
          
32
    public static class Builder {
33
 
          
34
        private ExpenseEntity expense;
35
 
          
36
        public Builder() {
37
            expense = new ExpenseEntity();
38
        }
39
 
          
40
        public Builder fromDTO(ExpenseDTO expenseDTO) {
41
            expense.price = expenseDTO.getPrice();
42
            expense.comment = expenseDTO.getComment();
43
            if (expenseDTO.getDate() != null)
44
                expense.date = expenseDTO.getDate();
45
            else
46
                expense.date = LocalDateTime.now();
47
 
          
48
            return this;
49
        }
50
 
          
51
        public Builder withUser(UserEntity user) {
52
            expense.user = user;
53
            return this;
54
        }
55
 
          
56
        public Builder withExpenseTypes(List<ExpenseTypeDictEntity> expenseTypes) {
57
            expense.expenseTypeDict = expenseTypes;
58
            return this;
59
        }
60
 
          
61
 
          
62
        public ExpenseEntity build() {
63
            return expense;
64
        }
65
    }
66
 
          
67
}



Then the creation of a new object in ExpenseService will look like:

Java
 




xxxxxxxxxx
1
14


1
@Override
2
@Transactional
3
public void addNewExpense(@Valid ExpenseDTO expenseDTO) {
4
    ExpenseEntity expenseEntity = createExpenseEntity(expenseDTO);
5
    expenseRepo.save(expenseEntity);
6
}
7
 
          
8
private ExpenseEntity createExpenseEntity(ExpenseDTO expenseDTO) {
9
    return new ExpenseEntity.Builder()
10
        .fromDTO(expenseDTO)
11
        .withUser(authenticationBO.getLoggedUser())
12
        .withExpenseTypes(findExpenseTypes(expenseDTO.getTypes()))
13
        .build();
14
}



Wait a second! Isn't this code a violation of the Creator (GRASP) pattern? Yes, it is! Generally speaking, almost half of the GoF patterns in some way violate something. For example, Visitor hates OOP, but sometimes there are situations when you just can't avoid using it. As we have already seen, it is not possible to write an enterprise project adhering to every principle, practice, and pattern. So we should ask ourselves that if we violated something, what consequences and benefits would it cause? In Builder's case, it will not mess up code. This pattern is hard to ruin. It is easy to understand its purpose and use it, especially for new programmers on a project. Therefore, its use is more than justified.

Many refactoring techniques are also unavailable. For example, Replace Method with Method Object: When we replace a method with a class that has the name of the method and in the constructor, it expects an instance of the caller class. The new class has only one method, compute(), which does the same thing as the old method. To call a new method, we create the new object and pass the caller class itself to it: new MethodObject(this). In the anemic model, the problem is simply moved to another layer, because it makes no sense to pass the object of the service as a parameter because the information is stored in local variables.

In our examples, it's hard to come up with some complex logic to justify using this technique, but imagine that we need to calculate all the expenses of a particular user based on many class fields. In this case, our method will not have local variables, and all of them will become fields of the new class, which can significantly improve the readability of the method. Then it will be easy to split the method into many smaller ones that will not pass 4 parameters from method to method. It will look like this:

Java
 




xxxxxxxxxx
1
49


 
1
@Data
2
@Entity
3
@Table(name = "user", schema = "expenses")
4
public class UserEntity {
5
 
          
6
    @Id
7
    @GeneratedValue(strategy = GenerationType.IDENTITY)
8
    @Column(name = "id")
9
    private Integer id;
10
 
          
11
    @Column(name = "email")
12
    private String email;
13
    ...
14
 
          
15
    @OneToMany(mappedBy="user")
16
    private List<ExpenseEntity> expenses;
17
 
          
18
    ...
19
 
          
20
    public Integer calculateAllExpensesPrice() {
21
        return new ExpensesPriceCalculator(this).compute();
22
    }
23
 
          
24
}
25
 
          
26
class ExpensesPriceCalculator {
27
    
28
    private List<ExpenseEntity> expenses;
29
    
30
    private Integer discount;
31
    
32
    
33
    public ExpensesPriceCalculator(UserEntity user) {
34
        // Copy relevant information from the expense
35
        ...
36
        this.expenses = user.getExpenses();
37
    }
38
    
39
    public Integer compute() {
40
        // Perform long computation.
41
        ...
42
        initDiscount();
43
        validateExpenses();
44
        filterExpenses();
45
        ...
46
        return calculateFinalPrice();
47
    }
48
    
49
}



Polymorphism in Domain Model

How can we use all of it in a Spring environment? We shall consider all of the limitations of the selected architecture, external services, and Spring itself. We know that RDBMSs don't support polymorphism, but there is a way to use it in the domain model, which is mapped to DB tables.

Do you remember the example of Replace Conditional With Polymorphism? Imagine that instead of ExpenseEntity in an anemic model we want to have abstract ExpenseEntity, which contains all shared fields and methods and its descendants: BasicExpenseEntity, SaleExpenseEntity, WholesaleExpenseEntity? Every class wants to have his own fields.

We have two options to achieve this. Use a single table that contains all of the columns, but then we need to make sure all NOT NULL constraints are enforced by triggers. Or we may use one table for common fields and separate tables for every subclass that will be connected by a Foreign Key. The first approach does not support Not Null constraints, which have to be handled by triggers. The second uses JOINs, which could be an expensive operation for large numbers of records if you use 4+ statements.

Example of polymorphic domain model:

Java
 




xxxxxxxxxx
1
81


 
1
// contains all shared fields and methods
2
@Entity
3
@Table(name = "expense", schema = "expense")
4
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) // we use single table inheritance
5
public abstract class ExpenseEntity {
6
 
          
7
    @Id
8
    @GeneratedValue(strategy = GenerationType.IDENTITY)
9
    @Column(name = "id")
10
    private Integer id;
11
 
          
12
    @Column(name = "price")
13
    private Integer price;
14
 
          
15
    @ManyToOne(fetch = FetchType.LAZY)
16
    @JoinColumn(name = "user_id")
17
    private UserEntity user;
18
    ...
19
    // other common fields
20
 
          
21
 
          
22
    protected Integer getBasicPrice() {
23
        // get the basic price
24
    }
25
 
          
26
    public abstract Integer getPrice();
27
 
          
28
}
29
 
          
30
 
          
31
// Casual expense, which does not have any specific fields
32
@Data
33
@Entity
34
public class BasicExpenseEntity extends ExpenseEntity {
35
 
          
36
    @Override
37
    public Integer getPrice() {
38
        // get the price for a casual expense
39
    }
40
    
41
}
42
 
          
43
 
          
44
// Expense that user made with the discount
45
@Data
46
@Entity
47
public class SaleExpenseEntity extends ExpenseEntity {
48
 
          
49
    @Column(name = "discount")
50
    private Integer discount;
51
    ...
52
    // other sale specific columns
53
 
          
54
    @Override
55
    public Integer getPrice() {
56
        // get price with the discount
57
    }
58
    ...
59
    // other sale specific methods
60
 
          
61
}
62
 
          
63
 
          
64
// Goods that user has bought in large amount
65
@Data
66
@Entity
67
public class WholesaleExpenseEntity  extends ExpenseEntity {
68
 
          
69
    @Column(name = "amount")
70
    private Integer amount;
71
    ...
72
    // other wholesale specific columns
73
 
          
74
    @Override
75
    public Integer getPrice() {
76
        // get the wholesale price
77
    }
78
    ...
79
    // other wholesale specific methods
80
 
          
81
}



Purpose

What the purpose of all of this? "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." I know that you have heard it many times. But do you really understand what it's for? 

For businesses, one of the most important things is how quickly a developer can make new functionality. For the developer, the main factor is the quality of the existing codebase (not taking into account the experience of the programmer). If our architecture and code are clean, the development process goes quickly, it saves the project owner's money, and increases our professional skill. But if we have spaghetti code, it could sometimes be impossible to add a new feature without refactoring the whole project, which can take weeks or even months of hard work.

I am sure that you are familiar with bugs that you need to fix quickly. We figured out what we need to do on the front-end, it calls some method on the server, we turn on the debug, and go through the long chains of methods in the service layer. Finally, there is a couple of 20+-line-long methods and in the end, you have found the problem. It takes a lot of time. You have to look at a lot of code that you are not interested in. It is much better to split the methods and keep the logic of the model in the model itself and access it in services that are responsible only for infrastructure logic. Then the number of methods will increase, which will have a positive effect on the readability of the code, as each method's name will be a kind of comment for the code it holds. The code will be encapsulated in separate classes. It would be easier to maintain the project, changes would be faster and cheaper, and developers would be more productive.

Conclusion

The Rich Domain Model sounds great in theory, as it allows you to write more quality code with fuller use of OOP — but it requires a professional team with programmers who know each other's programming style. On the other hand, the Anemic Domain Model is much easier to implement and maintain if you don't have a very experienced team, but it greatly cuts down on design capabilities and promotes a procedural programming style. Therefore, in the real world, you should try to find the balance and move logic into the domain model and leave the calls in services.

Such a "hybrid" approach gives us a significant advantage — we can divide the methods and put logic into the appropriate layers. This approach clearly splits the Model layer in the MVC architecture into Model and Service, makes test writing easier, and facilitates cleaner code by grouping methods more logically.

Topics:
anemic objects ,architecture ,domain model ,java ,layered architecture ,mvc ,polymorphism ,rich domain objects ,spring ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}