UseCase Precipitation and Reuse
Published: 2022-10-13 13:48:13

# Introduction

Through this article, you can learn:
1. What is a UseCase
2. Why do UseCase level abstraction
3. An example of a UseCase level SDK abstraction


# What is the UseCase

For an introduction to this concept, you can refer to the description of the "UseCase Layer" in Chapter 22 of "[Clean Architecture](https://learning.oreilly.com/library/view/clean-architecture-a/9780134494272/)":

> The software in the use cases layer contains application-specific business rules. It encapsulates and implements all of the use cases of the system. These use cases orchestrate the flow of data to and from the entities, and direct those entities to use their Critical Business Rules to achieve the goals of the use case.

![](http://www.ryu.xin/wp-content/uploads/2022/09/22fig01.jpg)

# Why do UseCase level abstraction

At the use case layer, with the continuous enrichment of business scenarios, the complexity will increase dramatically. When the scene details change, we don't want the changes in this layer to affect business entities, UI, etc. If a scene is not well abstracted, it is difficult to achieve logical isolation and scene-level reuse of different scenes. In TOGAF, there is a concept of "Enterprise Continumm". The key point of this concept is how to precipitate components at different levels for reuse:

![](http://www.ryu.xin/wp-content/uploads/2022/09/togaf.png)

* **Architecture Continuum:** This continuum can extract reusable components from a specific architecture into a repository (Gerneralization for future re-use) for similar services. In specific applications, reusable components can be selected from the component repository and adapted to the actual application scenario (Adaptation for use)
* **Solutions Continuum:** Similar to Architecture Continuum, in the face of different markets, it needs to be able to choose from a reusable solution library and quickly replicate. For delivery to emerging markets, it can also be extracted into a reusable solution into the asset library

UseCase level abstraction can be understood as a solution continuum. The biggest difference between it and function-level reuse is that at the UseCase level, it spans multiple business activities and multiple roles, and can achieve full-chain reuse in a certain scenario. For example, under the e-commerce system, we can summarize and summarize various transaction scenarios and transaction modes:

* Secured transaction mode: Secured transaction refers to the provision of a third-party guarantee account, the custody of transaction funds during the transaction process, and the transfer of funds is completed after the confirmation of the buyer and the seller. This method avoids online transactions, which may fail due to trust issues, and at the same time ensures the interests of both buyers and sellers
* Pre-sale transaction mode: The pre-sale transaction is a staged transaction. There will be two stages of deposit payment and final payment during the order placement process. Part of the cost is paid in the deposit payment stage, and the remaining cost is paid in the final payment stage. After the seller receives the balance payment, it will be shipped. This model is more commonly used in big promotion marketing activities, which can play a role in locking buyers, inventory certainty, etc.
* Electronic voucher transaction mode: Electronic voucher transaction refers to the transaction process of purchasing/receiving vouchers online, and then going offline to verify vouchers, and finally complete the transaction process of consumption or delivery. Its main feature is that it adopts an identity-based verification mechanism with credentials as the carrier. Common vouchers include: electronic exchange coupons, delivery coupons, electronic tickets, electronic membership cards, etc. The carrier of the certificate usually has the form of serial code, QR code, etc.

Let's take the online movie ticket purchase that is common in daily life as an example. In this kind of scene transaction, movie tickets are generally not mailed to consumers in the form of physical logistics, but are sent to consumers through SMS or App with a QR code or serial code. With this QR code or serial code, consumers can go to the cinema to collect tickets by themselves before watching the movie. Once the movie ticket is taken out, the electronic voucher will be cancelled and cannot be used again. This is a one-time write-off electronic voucher transaction mode.

For another example, we can buy and book a car 4S maintenance service online. After the reservation is successful, the merchant will send the service redemption code to the consumer via SMS or App. Consumers can use this QR code to go to car 4S stores to enjoy maintenance services, such as car washing. A car maintenance service might be a package, such as a package that includes 12 car washes. Then, the rights and interests contained in this electronic certificate can be written off multiple times.

It is not difficult to see that the electronic voucher transaction mode can be reused at the solution level by different forms of business. Business users do not need to complete the infrastructure for generating vouchers, issuing voucher codes, verifying vouchers, and returning vouchers. They just need to declare the use of this scenario/pattern and define rules on some special point, such as write off this point:

* Movie ticket business: It needs to be stated that when using the scene mode of electronic vouchers, his write-off method is "single write-off"
* Auto 4S maintenance service: It needs to be stated that when using the scene mode of electronic certificate, his write-off method is "multiple write-offs"

We can define the scene-level development SDK on the scene template of the electronic certificate. Whether we allow multiple write-offs for a certificate can be defined as follows:

```java
public interface ETicketTradeSDK extends IBusinessExt {

    String EXT_ETICKET_IS_SUPPORT_MULTI_WRITE_OFF = "EXT_ETICKET_IS_SUPPORT_MULTI_WRITE_OFF";

    @Extension(
            code = EXT_ETICKET_IS_SUPPORT_MULTI_WRITE_OFF,
            name = "Is Voucher support multiple write-off",
            reduceType = ReduceType.NONE
    )
    Boolean isVoucherSupportMultiWriteOff();
}
```

In the movie ticket business, when using the electronic voucher scenario, he can implement this extension point and declare that "multiple write-offs are not allowed", as follows:

```java
@Realization(codes = HiMovieBusiness.CODE)
public class HiMovieETicketExt extends BlankETicketTradeSDK {

    @Override
    public Boolean isVoucherSupportMultiWriteOff() {
        return false;
    }
}
```

Similarly, we can also take the pre-sale transaction model as an example. The pre-sale transaction is divided into two stages: deposit payment and final payment. However, different businesses have different requirements for the deposit payment ratio, some require a 30% deposit, and some only require a 5% deposit. Therefore, the pre-sale transaction scenario mode can also extract the extension point of "custom deposit payment ratio", and let each business decide on its own. as follows:

```java
public interface PreSaleTradeSDK extends IBusinessExt {

    String EXT_PRE_SALE_CUSTOM_DOWN_PAY_RATIO = "EXT_PRE_SALE_CUSTOM_DOWN_PAY_RATIO";

    @Extension(
            code = EXT_PRE_SALE_CUSTOM_DOWN_PAY_RATIO,
            name = "Custom PreSale Down Payment Ratio",
            reduceType = ReduceType.FIRST
    )
    Double getCustomDownPaymentRatio();
}
```

We assume that the movie ticket business also has pre-sale (such as large-scale live performances, concert scenes), and the pre-sale deposit ratio of movie tickets is required to be 40%. The business customization logic is as follows:

```java
@Realization(codes = HiMovieBusiness.CODE)
public class HiMoviePreSaleExt extends BlankPreSaleTradeSDK {

    @Override
    public Double getCustomDownPaymentRatio() {
        return 0.4;
    }
}
```

From the above two examples, we should be able to easily see. Customized for the UseCase level SDK, it will be more logical thinking. Development and products can be well consistent with the language, and the code is consistent with the requirements. When the business conducts logic customization, it does not perceive the underlying entity structure. The conversion of this structure and data is encapsulated by electronic vouchers and pre-sale transaction scene templates.

We all know that under massive data, the order structure stored in the database cannot be changed at will. We generally use some structured fields for business information storage, such as K/V structure, JSON structure, etc. Different business scenarios are finally stored on the order, and business information will be saved on this structured field. In the above example, whether the electronic certificate allows multiple write-offs is referred to the K/V structure. On the "save" behavior of the order entity, we can define an extension point called "custom order attribute", as follows:

```java
public interface OrderLineSaveExt extends IBusinessExt {

    String EXT_ENTITY_ORDER_LINE_CUSTOM_ATTRIBUTES = "EXT_ENTITY_ORDER_LINE_CUSTOM_ATTRIBUTES";

    @Extension(
            code = EXT_ENTITY_ORDER_LINE_CUSTOM_ATTRIBUTES,
            reduceType = ReduceType.NONE
    )
    Map<String, String> getCustomOrderAttributes(OrderLine orderLine);
}
```

In the electronic voucher transaction scenario, he can implement this extension point, so as to complete the expression with business semantics and complete the data mapping on the entity. as follows:

```java
@Realization(codes = EticketTradeUseCase.CODE)
public class ETicketTradeBusinessExt extends BlankOrderLineSaveExt {

    @Override
    public Map<String, String> getCustomOrderAttributes(OrderLine orderLine) {
        EticketOrderLineAbility ability = new EticketOrderLineAbility(buildEticketOrderLine(orderLine));
        Boolean supportMultiWriteOff = ability.isVoucherSupportMultiWriteOff();
        Map<String, String> output = Maps.newHashMap();
        output.put("e_multi_write_off", supportMultiWriteOff ? "1" : "0");
        return output;
    }
    ......
}
```

In this way, the code logic of the underlying entity layer will be very clean, and it will not perceive the details of the upper-level scene changes. Moreover, in this way, it is easy to deal with the superposition and combination of multiple scenes. For example, in the sample attached to this article, I simply wrote a business that uses both the electronic voucher scene template and the pre-sale transaction scene template. You can run: org.hiforce.lattice.sample.starter.LatticeUseCaseSample to observe the running results, the results are as follows:

```
[UseCase]PreSaleTrade load custom down payment ratio: .40
[UseCase]ETicketTrade is support multiple write-off: false
Save OrderLine id: 1, bizCode: hi.movie
-- Total Pay Price: 4000
-- Order Attributes: [e_multi_write_off:0]
```

For the sample code described in this article, you can visit: https://github.com/hiforce/lattice-sample/tree/main/lattice-usecase-sample

***
中文版：https://www.ryu.xin/2022/09/28/lattice-usecase-overlay/