How to use domain-driven design - field service

Original: how to use domain-driven design - field service

Outline

This article describes the domain-driven design (DDD) tactical mode Another very important concept - the field service. In two previous blog post, we have learned what is the value of objects and entities, and can be more clear positioning of their own behavior. But at some point, you will find some of the business behavior does not seem likely to fall into a single entity or value object body, and will be placed into this part of the business logic and confused. At this point, you may need to complete a field service operation.

So, in the end what is the field of services? How in the field of service areas found it? Traditional service areas and application services, what difference does it make? This article from a different perspective to bring to rediscover what "field service" concept, and gives the corresponding code fragment (code snippets in this tutorial are using C # , the latter part of the actual project is also based DotNet Core platform).

What is the services sector

Before you begin, or should I say it a little digression: If you read the previous articles in this series, probably will find that the style of the series are parsed from the beginning of the original, and then combined with their own actual number of cases and scenarios for the interpret some of the concepts in the field of drive. I do not know this way of writing so that we can more clearly understand, so if you have any suggestions, then you can leave a message in the comments section, I will carefully listen to your views and suggestions.

In the article, I will try to avoid all kinds of shorthand name (such as event source, some students prefer abbreviated as ES), although sometimes abbreviated indeed very convenient, but will make the cost of communication between people invisible by large, so in my blog post as long as no shorthand where I will not use shorthand.

Another point is that, more likely to belong to the early conceptual thing, so there is no ready-made github codes for your reference, we do not have much to worry about, after the completion of the concept of learning that several of us began our code time ( ● '◡' ●).

Back to the main topic, what is the field of services? Look original original "domain-driven design: the core software complexity response to it" concept mentioned in the service areas of:

In some cases, the clearest, most practical design will include some special operations that do not belong to any object conceptually. Rather they attributed what kind of forced, it is better to go with the flow introduced a new element in the model, this is the Service (Service).
When a process wants or conversion operation in the field of responsibility does not belong to the natural value of the object or entity, should be added in the model interface as a separate operation, and declared as Service. To use the language model defined interfaces, and to ensure that the operation is the name of the term UBIQUITOUS LANGUAGE. In addition, the Service should be defined as stateless.

Li Jie Viva

amount. . . . "Li Jie Long live." The reason this concept difficult to understand because: First, it assumes that we are looking into a number of areas "contain special operation", that is to say at this point we already have divided areas corresponding to various objects and its ability to act, then let us consider extract the legend of the "service" (that is, we in this subject area service). But often the reality is, as a beginner, we can not reasonably abstract each object, and does not think the experience of a good case to be. So read this concept of time is very confused, we could not find the concept of "these actions" is anything, it is even more can not understand what the Service is a.

“在自己的私人飞机里面玩儿电子游戏是什么感觉呢?   呃.....好像前提是我得有钱买一架飞机吧?”

Start from the actual scene

I think a number of ways to express "service areas", but it seems like a long time are not easy to make people understand. So start using the Bowen case to start thinking, I hope that everyone can understand the usefulness of this case the field of services.

To look at the article "How to use DDD - entity" a physical object that we extracted in:

public class Itinerary
{
    public int ID { get; set; }

    public List<Person> Participants { get; set; }

    public List<Address> Places { get; set; } 

    public ItineraryNote  Note { get; set; } 

    public ItineraryTime TripTime { get; set; }

    public ItineraryStatus Status { get; set; }

    //ctor

    public void ChangeNote(string content)
    {
        Note = new ItineraryNote(content);
    }
}

The entity object indicates the stroke of a trip. Currently, as an example, we only know that in this field allows us to modify Remarks travel information, so we in the article gives it a behavior modification notes.

According to the progress of the project, we are now captured another demand: if the trip does not end users access to the travel, the system recommended for users based on the location the user is currently located near the delicious food.

This is a very user-friendly and useful features, but also the other products of the same type of products and systems competitive advantage. So we should place it in the field to consider. From the description of the functional requirements, we need to do is a food recommended behavior. But let us, paradoxically, it is recommended that a food movement, we should it belong to who? To journey? Let the journey entity to recommend dishes? Obviously, you did not do it. The journey is only concerned with basic information about this trip, place, characters and time, we do not recommend this action to its cuisine, make it a versatile machine.

To review the above mentioned concept: " In some cases, the clearest, most practical design will include some special operations that do not belong to any object conceptually. " Carefully read several times, Nani? This is not to say that this is the situation? Now in this case, we recommend there is a food operation, but it does not belong to any object.

When we arrived at this point, we might have a little understanding of the services sector. Next, we continue to go down. Now, we have to understand, we may need a Service to handle this operation. Try to establish a RecommendFoodsService .

public class RecommendFoodsService
{
    public List<RecommendFoodInfo> RecommendFoods(Itinerary currentItinerary)
    {
        //todo
    }
}

In the services sector, there is a method RecommedFoods, which is to get through the current journey, returns a list of recommended dishes. It may be the internal implementation of such :( Here we assume Itinerary of Places in last place is our current location, and we already have a restaurant called the Restaurant a series of information entity that provides information about restaurants and behavior. of course, you can build your own restaurant to try such an entity, in order to deepen the impression of solid section)

public class RecommendFoodsService
{
    public List<FoodInfo> RecommendFoods(Itinerary currentItinerary)
    {
        var recommendFoods = new List<FoodInfo>();

        //Get Last Address
        int lastCountIndex = currentItinerary.Places.Count -1;
        var currentAddress = currentItinerary.Places[lastCountIndex];

        var nearbyRestaurants = Restaurants.Where(s=> s.Address.isNearby(currentAddress)).ToList();

        foreach(var restaurant in nearbyRestaurants)
        {
            var food = restaurant.GetRankNoOneFood();

            recommendFoods.Add(new FoodInfo(food,restaurant.Address));
        }

        return recommendFoods;
    }
}

OK, so far we have completed a demo version of the service areas, in the service, us get to the position of the current journey, according to the position, a collection of restaurants exist from the system to find the location nearest restaurant distance and then recommend the best restaurant in one of these rankings evaluate dish to the user.

Take a look at the above behavior in which things appear, first of our trip, and a restaurant. Reasonable process relationship between two entities, we have completed our series of operations, food and returns a collection of information (restaurant information here we define a value for the object). Note that although we have a number of entities which contains several values and objects, as well as the use of different behavior between them, but this food is recommended from a behavior point of view, they are actually a whole, the processing logic is inextricably linked ( knock focus !!!).

Closer to reality

The above version we will him as a demo version to define, because in actual situations, we often through the store to get the information entity collections (Repository, information about the content will be introduced later in the article) of , just as in the code above . Restaurants . There may be closer to the reality of our code is similar to the following, but we can not consider such an approach, because it involves the repository (warehousing Repository) and aggregate root (AggregateRoot) concept, and now we just need to good understanding of field service just fine.

 public List<FoodInfo> RecommendFoods(int currentItineraryID)
    {
        var recommendFoods = new List<FoodInfo>();

        //Get Last Address
        var currentItinerary = itineraryRepository.Get(currentItineraryID);
        int lastCountIndex = currentItinerary.Places.Count -1;
        var currentAddress = currentItinerary.Places[lastCountIndex];

        var nearbyRestaurants = restaurantRepository.GetNearbyRestaurant(currentAddress);

        foreach(var restaurant in nearbyRestaurants)
        {
            var food = restaurant.GetRankNoOneFood();

            recommendFoods.Add(new FoodInfo(food,restaurant.Address));
        }

        return recommendFoods;
    }

Come on, now according to our understanding and discovery of content, take a look at some of the features of the service areas:

  • Service areas are treated in the field of objects such as entities, and so the value of the object
  • Field service scheduling process is responsible for a series of objects on the field
  • When we find that an action can not be assigned a value object or entity, and the operating and business processes is very important, we often need to use the services sector
  • Field service operations, from the perspective of the field of view, it is a whole

If you are making the following operations, it may prove you need a field service:

  • By A and B, to give a C.
  • A need for a cumbersome internal policies in order to get a result B.

(Ps: A, B, C refers to the field value in an object or target entity)

VS field service application service

In fact, in the field of drive in use, there is a service called the application services, application services are divided in the service application layer. And often because the service is called, it is difficult to distinguish it from all service areas What is the difference, the end result is either caused by the application service very large (all logical layout are handled in the layer), or is very weak application services (it is a calling code field services). Similarly, when an application service began to confusion, field service will become confusing, because the logic of the original field of services you may give the application services, application services and the logic gave the service areas.

Before the two comparison, take a look at four architecture diagram as we provide the traditional domain-driven design:

Four DDD

Can be seen from the figure, a reference to the application layer to maintain the relationship between the domain layer, that is to say in the application layer, you can access to domain objects. So let the application layer also has the ability to schedule domain objects . This is our domain objects and features of the same, so in many cases, we distinguish between the difficulty of application services and field services on the increased.

About application services, because in the original I did not find the corresponding key statement, so choose some conclusions online for your reference:

Application service is the primary means use cases and user stories (User Story) expression.
The application layer to expose the full functionality of the system through the application service interface. In the realization of the application service, which is responsible for orchestrating and forwarding it to achieve the function entrusted to one or more areas to achieve the target, which itself is only responsible for the execution order of business use cases as well as the results of the assembly.

From the above conclusion we can probably know, the application service is to allow applications to use and supports external users to access objects and perform field logical field level. Like in dotnetoore, users can access our business objects defined by visiting our controller, and can also be exposed through the controller interface to perform the business logic.

Therefore, we can be considered as an intermediary application services execute business logic (so defined may not very good), it did not involve any logical process core areas , it is responsible for some validation, support and other components (such as logs, performance monitoring, etc.).

Extending the above requirements

In the above recognition field service, we have captured such a demand: "If the trip is not over, user access to the route, the system will be recommended for the user depending on the location the user is currently located near the delicious food." Later, demand has increased one: "we can use text messages to notify the food to the customer."

So consider such a demand, we ought to realize this function SMS notification Where did I put it? Or texting operation where this behavior on it? Let's consider him to be placed in service in the field:

public class RecommendFoodsService
{
    public List<FoodInfo> RecommendFoods(Itinerary currentItinerary)
    {
        var recommendFoods = new List<FoodInfo>();

        //Get Last Address
        int lastCountIndex = currentItinerary.Places.Count -1;
        var currentAddress = currentItinerary.Places[lastCountIndex];

        var nearbyRestaurants = Restaurants.Where(s=> s.Address.isNearby(currentAddress)).ToList();

        foreach(var restaurant in nearbyRestaurants)
        {
            var food = restaurant.GetRankNoOneFood();

            recommendFoods.Add(new FoodInfo(food,restaurant.Address));
        }

        //在这里添加短信发送?
        SmsUtil.Send(currentItinerary.Participants,recommendFoods);

        return recommendFoods;
    }
}

We on the basis of the original code, add a line of code, to realize its SMS notifications, and now this has met our needs. but! ! ! ! SMS notification will be placed here, okay? To solve this problem, we need to consider: "SMS is my field extracted behavior?" "Without this behavior, have any effect on the business logic?"

And think about texting field is extracted out of it? We have been concerns about the journey, it is clear that the object of various journey is our main concern. So texting is not something we have extracted, it just needs our support functions included with nothing.

So without this behavior, have any effect on the business logic of it? It will not affect my complete gourmet recommend this behavior? Obviously, not! Remember the above characteristics we say it's a field services: operation in the field of services, from the perspective of the field of view, it is a whole . If the whole of the loss of part of it can not complete a business. So now the recommended food business, if a portion of the restaurant look like it removed? OMG, this service has been abolished, it has lost its function. If you send text messages that remove it? It does not seem a little affected.

Then the message is sent, where in the end put it? Application service! ! ! ! !

public class ItineraryApplicationService 
{
    public string RecommendFoods(int currentItineraryID)
    {
        Logger.Log("执行推荐美食业务");

        var participants = itineraryRepository.Getparticipants(currentItineraryID);
        var foods = RecommendFoodsService.RecommendFoods(currentItineraryID);

        SmsUtil.Send(foods);

        return foods.toJson();
    }
}

We define a named at the application layer ItineraryApplicationService application services, it provides an outside RecommendFoods interface client (App, web pages, etc.) can be accomplished recommend cuisine series of operations through the API. Recommended food behavior we have encapsulated in the field of services, application services do not need to know the internal logic of the operation can be completed, which also confirms our above said point: From the perspective of the field of view, the services sector as a whole .

The most common authentication and authorization services sector it is

In general applications, the application authentication and authorization services. why? Because it is often only to maintain the system allows you to provide a basic functionality, but must not be performed in your field. Perhaps, this is not easy to understand, so we have to try to define it as service areas to look at. Consider the example into texting, we implemented a wrong version of the field service, we now send text messages to the field of services to replace the identity validation code, and then placed in the method block first. bring it on? Continue to answer the above questions, they are a whole do? If stripped of this code, have any effect on behavior? Slowly you will it come from the services sector in the past.
But if you are implementing a competence in software, it may be defined in the field. Because a series of operations is certified in your field, you need to seriously think about it, once authenticated code may lose your application will not be able to provide normal function.

Use the field service

Experts in the field and you've talked about the concept of multiple entities involved in the field, but you're not sure which entity "owns" behavior. This behavior does not appear to belong to any one entity, but when you try to force the adaptation to the behavior of any entity to deal with them will be a little tricky. This mode of thinking is the need for strong signs of field services. [Hush, my copy of this sentence is. (* ^ __ ^ *)]

Do not use too many service areas

It is not the only area of the object field service scheduling to value objects and entities so what? Of course not, the application service is also available.
It is also a common problem everyone: all entities, value objects, warehousing and field service orchestration through complete business logic. Very thin so that the application service layer, often only one line of code that calls the art and services (logging, performance codes automatically by some prior frame).

Attempt to assign permissions to the application part dispatch service , it will not affect your area code readability, it will make reading more clear. When you find your calling behavior only logical arrangement between entities or value objects, but does not constitute a complete business practices in the field of time (such as a trip to get Api expressed Location Distance function, you can not have this function consideration for the service areas in the application service by passing the ID, to obtain the address of this trip itinerary in the warehouse, and then from the conversion to the system to calculate the distance, and then returned to the client), consider it to application services.

Do not give too much of the behavior of the services sector

Why do you say? If you find that you build a model in the field, the value of the entity and the behavior of objects just a little sporadic, and the real value of objects and actions to achieve the behavior of operations are done by field service. Well, you might use the wrong service areas , to re-know you identified entities and value objects, giving them their own behavior, delete the wrong service areas.

to sum up

This time we introduce the domain-driven design tactical mode service areas . Also compared the areas of services and application services, which in part may not be too full description, I hope everyone from the difference between the two examples is understood that if the latter would have time to write a blog for everyone to distinguish between specialized field services and application services. In the process of explaining, we also relates to the other concepts all tactical modes, such as Repository and AggregateRoot, these two concepts will be introduced to bring everyone in the latter part of the article.

  • Comments on the 15th floor in @todo friend gave a good suggestion, then it is time to writing ignore the problem.

 
 
 

Small eggs

Highly recommended now released a cartoon movie for everyone , "and if you carpool on the waves" . Like animation students can not miss.
"If we can carpool with you over the waves."

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12065794.html