Write High Quality Maintainable Code: Logical Judgment. If you want to get more original articles, please search our official account

What is data modeling

Data modeling is a process for defining and analyzing the requirements for data and the corresponding support for their needs for an information system.

As the interaction of the front-end page becomes more delicate and complex, the state originally stored in the server side is placed in the front-end, and the state management library such as Flux, Redux, MOBx, DVA, Rematch and VUex has become the standard configuration of each project.

Because of the popularity of layering, front-end engineers need to focus more on data management, and data modeling has become a fundamental skill.

The product of modeling is data model. Data model is a model that defines how data is input and output. Its main function is to provide the definition and format of data for information system.

Data model includes data structure, data operation and data integrity constraints.

The simple idea is that a data model provides a “mold” where data is placed according to preconceived designs and constraints.

The three elements

Data integrity constraints

Good data structures must have constraints, such as the fact that the fields describing the same state are sometimes strings and sometimes numbers, which can lead to unexpected situations. Adding constraints ensures that the data is as clean as possible;

// Status is a string
if (status === 1) {... }Copy the code
// According to certain constraints
model.define(
  'user',
  {
    name: { 
      field: 'name'.type: STRING(64),
      allowNull: false.comment: 'name',},sex: {
	  field: 'sex'.type: INTEGER(1),
      allowNull: false.comment: 'gender',}});Copy the code

The data structure

In addition to describing the nature of the model itself, it is necessary to express the relationship between the model (table) and the model through some fields.

Data manipulation

The manipulation of data or the relationships between data on a data structure.

Domain-driven design

When developing applications around data models, how do we model them?

In fact, methodologies such as domain-driven Design (DDD) are widely used in the software development industry.

Before software development, it is usually necessary to sort out the business knowledge first, then to the level of software design, and finally to the development. In the process of business knowledge sorting, we will inevitably form a certain domain knowledge. The basic concept of domain-driven design is to drive software design step by step according to domain knowledge. In a nutshell, domain-driven design focuses on streamlined business models and implementation matching.

Layered architecture

A layered architecture based on domain-driven design allows applications to be layered

  • UI layer: Responsible for presenting information to the user and interpreting user commands.
  • Application layer: The activities used to coordinate applications. It contains no business logic; It does not retain the state of the business object; But it keeps the progress state of the application task.
  • Domain layer: The core of the business software. The state of the business objects is retained here, and persistence of the business objects and their state is delegated to the infrastructure layer.
  • Infrastructure layer: support inventory for other layers in. It provides the communication between layers, implements the persistence of business objects, and supports the user interface layer.

Following this hierarchy, the code changes more frequently as you go to the left. As businesses become more complex, the boundaries between the application layer and domain layer become blurred, and the domains tend to become intertwined.

Good design should avoid too many dependencies between layers, because if the code is not clearly isolated into a layer, it can quickly become confusing and difficult to maintain.

Through the design idea of layered architecture and high cohesion and low coupling, the system finally achieves a good consistency with the requirements, and responds quickly to the changes of requirements in business iterations.

entity

Entities are required objects in the domain model, and they should be considered at the beginning of the modeling process. For example, to realize the concept of “Cat”, we may create a Cat class, which may contain the name, gender, breed and other attributes, but these attributes are not enough to distinguish the Cat, so we need to create a unique ID to distinguish them, that is, to distinguish the identifier of the entity.

There are many ways to create an ID, it can be a primary key, it can be external, it can be generated by the system itself, but it must conform to the identity differences in the model.

The value object

An object that describes a particular aspect of a domain without an identifier is called a value object. For example, a point Customer on the canvas would be associated with name, province, city, district, and street. It is best to separate the address and keep references to the address, because they are all the same address property.

service

You can simply think of behavior as a service. For example, if you go to a store to buy something, your friend can also buy something. Putting the ability to buy as an attribute in the Person entity is obviously a bit of a mistake, because the “go buy” function doesn’t belong to you or your friends (entities or value objects), and going to buy might also involve goods objects.

It is important to keep services single and isolated, and to distinguish between domain services and application services. Deciding which layer a service should belong to is very difficult, and we need to make sure that the domain layer is isolated from the other layers when we model it at design time.

The module

A module is a method used to organize related concepts and tasks in order to reduce complexity, usually consisting of functionally or logically integrated elements to ensure high cohesion, and exposed to third parties through interfaces to reduce coupling between modules.

The aggregation

Aggregation is a group of related objects that can be considered as a unit for changes in data. The aggregation is based on (and only has) one entity (root) through which the aggregation is externally accessed and can refer to any aggregation or be referred to by other aggregations. Here is a simple aggregation example: the customer is at the root of the aggregation, the rest of the information is internal to the customer, and a copy of the address is passed around if it is needed (especially in Javascript).

The factory

Factories are used to encapsulate the knowledge necessary for object creation, and they are especially useful for creating aggregations. A factory method is a method of an object that contains and hides the knowledge necessary to create other objects.

The repository

The repository exists as a storage point for globally accessible objects. It is a separate layer, between the domain layer and the data mapping layer (data access layer). Its existence makes the domain layer unaware of the existence of the data access layer, and it provides a collection-like interface for the domain layer to access domain objects.

Data modeling for the front end

Data modeling is closely related to the back-end work, and the front-end data model is more dependent on the data transfer object (DTO) passed by the back-end for secondary construction. Whether the secondary build takes place in the server-side aggregation phase or the client-side AJAX request completion phase, the front-end needs to participate in some data cleansing and apply it to the front-end data model.

Field division

Now you can start trying to divide the business areas within your app. Take a mall as an example. It might include users, goods, shelves, orders, billing, accounts, and so on.

Each business domain can be split into at least one domain, organizing code by business domain, for example, in the transaction domain by the following directory structure:

src modules ... Trading # trading components/ # models/ # Models Pages / # redux/ # redux Services / # trading module related API styles/ # trading module styles index.ts ...Copy the code

The conceptual model

The premise of data modeling is a full understanding of business. A full understanding of business is equivalent to viewing the relationship between businesses from a higher perspective, which is conducive to better model construction.

Try to think back to the business (application) scenarios you are maintaining. Do you have a clear understanding of the relationships and interactions between business scenarios and business objects?

Using mind maps to sort out conceptual models, this stage can be done without strictly following the three elements and with goals that clearly express the real world.

Define the model

The definition model can be based on the conceptual model to complement details and relationships, such as simply defining a marketing product:

The above shows an activity area divided on the shelves of the shopping mall. The rule is to subtract XX from XX after full XX, the commodities participating in the activity will be put on the shelves in the area.

Reduce complexity

In most cases, especially when presenting logic, the front end should not be logic heavy.

Taking commodities as an example, there are complex price systems hidden behind different marketing types of commodities. Although it is the same marketing type, the prices of commodities displayed in different states may not be the same. You can imagine the fields behind this, and the calculation rules.

If the back end throws these fields, prices, and rules at you, picking them, not to mention front-and-back symmetry, can make your head spin.

It is better to avoid dealing with complex business decisions in the front end (client side) and to do so in the aggregation layer or in the back end.

Especially in the SCENARIO of C-side, data straight out is more important, and front-end students also have more time to do performance optimization. .

Another benefit is that if there is a presentation problem, you only need to make sure that the fields read are correct, and the rest only needs to be checked by one person.

// Bad
const switchPrice = product= > {
  switch(product.status) {
    case 0:
    	return product.priceA;
    case 1:
    	return product.priceB;
    case 2:
    	return product.priceB;
    default:
    	return  product.priceBase;
  }
}
<Price value={switchPrice(product)}/>
     
// Good
<Price value={product.price}/>
Copy the code

Logical layering

Design needs to distinguish between application logic (business logic) and presentation logic. The application layer focuses on the scheduling of the domain layer and is the implementation of business logic, while the presentation layer focuses on rendering and interactive actions.

In a large project, the same Model can be referenced multiple times, and you can’t be sure who will ultimately do what with the same data.

At the same time, only the abstract structure of the data source is retained in the Model, and the content of the data source is not modified.

// Only display logic is done in the view layer
/ / component A. <><span>Date: {format(res.date, 'YYYY-MM-DD')}</span>
</>

/ / component B. <><span>Date: {format(res.date, 'YYYY-mm ')}</span>
</>
Copy the code

Unified field

When designing the model, try to keep consistent fields with the back end. For example, some form scenarios require an extra layer of transformation during the echo and submission, and later maintenance will bring an extra layer of mental burden. In a separate development mode, there is no guarantee that the backend will present the fields first. My habit is to mark the fields, and then replace them globally.

Simplifying fields, clarifying semantics, and changing unreasonable front and back end interactions are fundamental to good data modeling, otherwise you will spend a lot of time understanding the meaning and calculation rules behind these fields.

summary

There is no perfect data model that can be applied to any demand scenarios. The implementation of the model needs to consider the actual business scenarios and technology selection comprehensively. When building a model, train yourself to think systematically and see the business from a higher perspective to create a model with a longer life span.

Recommended reading

Write high quality maintainable code: Optimize logical judgment

Front-end document site construction scheme

, recruiting

ZooTeam, a young passionate and creative front-end team, belongs to the PRODUCT R&D department of ZooTeam, based in picturesque Hangzhou. The team now has more than 50 front-end partners, with an average age of 27, and nearly 30% of them are full-stack engineers, no problem in the youth storm group. The members consist of “old” soldiers from Alibaba and netease, as well as fresh graduates from Zhejiang University, University of Science and Technology of China, Hangzhou Electric And other universities. In addition to daily business docking, the team also carried out technical exploration and practice in material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, promoted and implemented a series of internal technical products, and continued to explore the new boundary of front-end technology system.

If you want to change what’s been bothering you, you want to start bothering you. If you want to change, you’ve been told you need more ideas, but you don’t have a solution. If you want change, you have the power to make it happen, but you don’t need it. If you want to change what you want to accomplish, you need a team to support you, but you don’t have the position to lead people. If you want to change the pace, it will be “5 years and 3 years of experience”; If you want to change the original savvy is good, but there is always a layer of fuzzy window… If you believe in the power of believing, believing that ordinary people can achieve extraordinary things, believing that you can meet a better version of yourself. If you want to be a part of the process of growing a front end team with deep business understanding, sound technology systems, technology value creation, and impact spillover as your business takes off, I think we should talk. Any time, waiting for you to write something and send it to [email protected]