简体   繁体   中英

3-tier Architecture business logic

I have a question about Service Layer - now my controllers interacts with Service Layer where I work with EF Context but sometime business logic inside Service methods can be really huge approximately 1000 lines. For example:

class OrderService {

   public async Task UpdateOrder(OrderDto dto) {

      if(dto.Products.Count > 3)
      {
         **change order status that can take 300 lines**
      } 

   }
}

Where can I keep that logic that I use inside if statement ? Usually I just create private method inside that service but I'm not sure that it is a good approach. Maybe create specific class for that or something like this ?

Thank you.

This question can go more to the developer's personal point of view. Here's some techniques I use to organize my code. Just try to see if they fit your scenario and change them to your need.

  1. Move some logic to your entities.Example: An entity should be able to know if is in a good state.

Entity.Type = Square

Entity.Edges = 3

Entity.IsValid() => False // Squares has 4 edges

  1. You can create multiple classes that will help you add some logic to your code. In a feature/entity you can create multiple validation classes and then do something like entity.AddValidation(EdgeValidator) .

  2. If you'll have a different algorithm base on conditions you can use the Strategy Pattern which is a Behavioral patterns .

If House.FamilySize == 1 then ProcessAlgorithm = SinglePersonAlgorithm

Else ProcessAlgorithm = MultiplePersonAlgorithm

ProcessAlgorithm(House)

  1. The old and classic split a function in multiple ones.

Incapsulating different branches of if statements in separate classes may require some rework and refactoring but may well lead to great results and allow you to use patterns like for example

  • Chain of responsibility
  • Pipeline processing

and eventually all other Behavioral patterns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM