A case of entity class design under DDD guidance

Source: Internet
Author: User
Tags date now
1 Intro

The tool class code in project development always grows with the development of the project, in the company many common code, the author discovers a simple, is also frequently used class: Basedomain, aroused my thinking.
In our company's development habits, database entity classes usually inherit a class called Basedomain, which is simple enough to populate the properties common to some database entities, and is designed as follows:

@MappedSuperclass <1> Public
class Basedomain {

    private Boolean deleteflag; <2>
    Private Date Deletedate;
    Private Date lastupdatedate;
    Private Date createdate;
    @Version <3>
    private Integer Version;

    @PrePersist <4> public
    Void, init () {
        date now = new Date ();
        Deleteflag = false;
        CreateDate = Lastupdatedate = Now;
    }

    @PreUpdate <4> public
    Void Update () {
        lastupdatedate = new Date ();
    }

}

A small class in fact still contains a lot of knowledge points in the inside, at least can contain the following points:

<1> after being inherited by another class, the fields of the parent class are not ignored, which means that the subclass does not have to write this heap of common properties on its own.

<2> tombstone Identity, the deletion of the business class must be the behavior of this identity and cannot be physically deleted. It is worth mentioning that the company's original field was named Isdelete, which does not conform to the specification of variable naming, will cause some serialization framework problems, and delete is the database reserved word, so this article with Deleteflag.

<3> using version as an implementation of optimistic locking, the self-increment of version and the exception of versions is affected by the @version annotation, and is controlled by the framework.

<4> Create date, update date and so on, after we use the JPA Save method, the framework automatically populates the corresponding values. 2 Discovering problems and solving problems

What is the frequency of this base class use? Every class. Yes, every developer of the company always prioritizes XXX extends basedomain when adding an entity class. Novice developers always have what to learn, they see the company's original code will inherit the class, and the surrounding colleagues also wrote that they do not even know the implementation of version optimistic lock, do not know the date the creation date of the class is declared in the base class , advanced developers can master the technical points I have mentioned above, although there are some discomfort in development, but they are also overcome as much as possible.
Wait, the above mentioned the addition of this base class, the development caused a discomfort, which aroused my thinking, the following to talk about the intuitive what is the discomfort and solutions. 2.1 No physical deletions, only tombstone

The real delete operation no longer occurs, and the physical deletion operation is replaced by Setdeleteflag (true). In the list display, you can no longer use the findall () operation, but you need to use Findbydeleteflagfalse (). More database query operations, take into account that the deleteflag=true of those records, should not be affected.

solve the problem : in DDD, the preferred way is to use the specification model to solve this problem, corresponding to the actual development, that is, JPA predicate, or familiar with hibernate people understand the criteria. But the inevitable point is that only the logical deletion, resulting in our database is getting larger (the solution is not no, it is the EVENTSOURING+CQRS architecture, this is a high-level practice of DDD, this article is not discussed). From the point of view of technology development, this does make our coding slightly more complicated, but its business significance is much larger than this development effort, so it is worthwhile. 2.2 cascading queries become troublesome

A member has multiple mailing addresses and multiple bank cards. reflected in the physical design, that is:

public class Member extends basedomain{

    private String username;
    @OneToMany
    private list<memberaddress> memberaddresses;
    @OneToMany
    private list<bankcard> bankcards;

}

Among them, memberaddress and Bankcard all inherit the Basedomain. Using the cascading features of the ORM framework, we could have checked out the member's information by passing through the corresponding mailing list and bank card list. But now is not so good, the use of cascading queries, you may be able to query the Memberaddress,bankcard has been deleted, only at the application layer to make deleteflag judgment, thus filtering the deleted information, this cannot be avoided, because the framework does not recognize the tombstone identity.

solve the problem: This question and the 2.3-verse question are the only things that have contributed to my intention to write this article, which is inextricably linked to DDD. DDD divides objects into entities (entity) and value object (Value objects). If you carefully analyze the above business and understand a little ddd, you will immediately realize. The member object is an entity, and memberaddress and Bankcard are value object (username is also value object). An important feature of value object is that, as an entity modification, from a business perspective, memberaddress and Bankcard are indeed a collection of abstractions to better describe member information. Another characteristic of value object, immutability, guides us,should not let Memberaddress,bankcard inherit Basedomain。 Having said that, I want to get rid of this habit from a theoretical height and let those who design a new entity inherit basedomain. After the value object loses the properties such as Deleteflag,lastupdatedate, some doubts may arise, and they will claim: "There is no lastupdatedate field in the database member_address this table, I can no longer know the last time this member's address was modified! ". Yes, from a logical point of view, the address has not changed, but the change is only the member's own address, this updatedate field is extremely unreasonable in the address, should be the member's modification. The actual development experience tells me that once so many value object inherits the related property that basedomain,99% does not use, and if it really needs to be used, add it to the class individually instead of inheriting basedomain. Second, these prisoners made another mistake, and when we design a system, we should be the entity first, not the database first. DDD tells us a great taboo of software development, and by 2017, there are still big help people asking: "I want to achieve the XXXX function, how my database should be designed." "These are the fundamental mistakes that make the software's purpose wrong and what the software is doing." is to study how to use computers to solve real (domain) problems, rather than to study how data should be stored more rationally. There are a number of new programmers in my company who hope that this will help those "misguided" practitioners "go straight." Software design should be from "database-driven" to "domain-driven", and DDD's practical experience is to design and develop large and complex software systems to provide practical guidance.2.3 Embarrassing position of optimistic lock

Again, the Version field in Basedomain, because value object such as Memberaddress and Bankcard is also given an optimistic lock behavior, which means that the lock granularity is smaller. Under the guidance of DDD, changes can also be understood as being emitted by the root of member, which is controlled by the version in member, which makes the lock granularity larger. In other words, from a technical development perspective, the value object plus version can allow simultaneous (OS level real) modification of a user's address information and bank card information, or even different cards in multiple cards, and separately controlled by member, means that The system can only perform a single operation at the same time. In the general perspective of business concurrency, a user will not have multithreaded modification behavior. From the point of view of software design, adding version to value object alone destroys the immutability of value object and should be replaced by the whole.

solution : In general, do not add an optimistic lock for value object. If there is a scenario where your value object needs to be versioned, there are two possible scenarios: 1 Your value object is not a value object at all, possibly an entity 2 aggregation root partition error ... There's no way to talk, right? 3 Summary

Basedomain Such a design itself is not the focus I want to emphasize, but since the emergence of basedomain such a design, then it should be what kind of entity to inherit, it needs to be considered. DDD, the identification of aggregate Root,entity,value object, is the core point of the entire software design, in this article, the judge whether to inherit the basedomain premise, that is the object is an entity, or value object. We all exist in the database, but the status is not the same.

If there are any deficiencies in this article, we welcome ddd enthusiasts to point out.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.