zoukankan      html  css  js  c++  java
  • How much business logic should be allowed to exist in the controller layer?

    How much business logic should be allowed to exist in the controller layer?

    As little as possible. Preferably none.

    The controller should be concerned with accepting the request, asking the correct domain service to process the request, and handing off the response to the correct view.

    In that process, all of the "business logic" should exist in the domain services.

    If you have functionality that takes domain objects and creates viewmodels out of them, then that can reasonably coexist with the controller. But that should be code that exists only for the sake of the corresponding views. If there is a business-level rule about data sanitization, that should exist in your domain/service level (with the approriate unit tests).

    The term "business logic" is one that is often confusing because people have different opinions about what this means. In my view, the term "business logic" covers two areas

    • Domain Logic
    • Application Logic

    Domain Logic is logic related to the core area that you business relates to, so if writing an application for accountants, then tax rules, book keeping rules, etc. are part of domain logic.

    Application logic is logic related to the fact that you are running a computer program. This can be stuff such as CSV import export, wizards, etc. Could also contain stuff like creating forgotten password emails.

    The kind of "business logic" that you can place in the controller layer is Application logic. Maybe not all application logic should go there. But you should never place domain logic in the controller layer. That should obviously be in the domain layer.

    You were talking about logic to format or sanitize data. Formatting must definately be application logic. Sanitizing on the other hand could be domain logic, if sanitizing data is based on domain rules. That depends on the context.

    ASP.NET MVC - Should business logic exist in controllers?

    Business Logic should not be contained in controllers. Controllers should be as skinny as possible, ideally follow the patter:

    1. Find domain entity
    2. Act on domain entity
    3. Prepare data for view / return results

    Additionally controllers can contain some application logic.

    So where do I put my business logic? In Model.

    What is Model? Now that's a good question. Please see Microsoft Patterns and Practices article (kudos to AlejandroR for excellent find). In here there are three categories of models:

    • View Model: This is simply a data bag, with minimal, if any, logic to pass data from and to views, contains basic field validation.
    • Domain Model: Fat model with business logic, operates on a single or multiple data entities (i.e. entity A in a given state than action on entity B)
    • Data Model: Storage-aware model, logic contained within a single entity relates only to that entity (i.e. if field a then field b)

    Of course, MVC is a paradigm that comes in different varieties. What I describe here is MVC occupying top layer only, vide this article on Wikipedia

    Today, MVC and similar model-view-presenter (MVP) are Separation of Concerns design patterns that apply exclusively to the presentation layer of a larger system. In simple scenarios MVC may represent the primary design of a system, reaching directly into the database; however, in most scenarios the Controller and Model in MVC have a loose dependency on either a Service or Data layer/tier. This is all about Client-Server architecture

    Factoring Application Code with ASP.NET MVC

    Because ASP.NET MVC is a web platform technology built around a design pattern, following the MVC pattern is a key step in properly factoring your application logic. Well-designed MVC applications have controllers and actions that are small and views that are simple. Keeping your application code DRY (Don't Repeat Yourself) as the application is built is far easier than trying to clean it up later.

    The routes you create in global.asax.cs define the URL hierarchy of your application. Defining your URL strategy, routes, and controller topology early in a project can help prevent having to change your client application code later.

    Because the majority of the application logic is contained within the models, MVC applications contain different kinds of models:

    • View models are built solely单独地,仅仅 for a view to data-bind against. These models are contained within the MVC application and often follow the same composition hierarchy as the views. They are focused on presentation. That is, they are only concerned with presenting data in the UI. Sometimes a special type of view model, called a form model, is also used to represent the data coming into an application from the user.
    • Domain models are based on the solution domain. They are focused on handling the business logic of the application. They represent the logical behavior of the application independent of the UI and the storage mechanism. They may be annotated or extended to support some application features such as validation or authentication. Because these models need to be shared between the server and client browser, they are sometimes contained within view models. Domain models are sometimes referred to as application models or service models.
    • Data models are built for data services and storage. These are not exposed by the application and are often encapsulated by a services layer.

    Organizing your application into these categories is a way of separating concerns in your code. This separation becomes increasingly important as an application grows in complexity. If you find that changes to your application logic are affecting storage or presentation (or vice versa), you should factor the code into separate models.

    In some cases, the models may be very similar to one another. In other cases, the models may radically彻底地 diverge. If your domain model and your data model are very similar, you can consider aggregating an instance of your data model class into your domain model class. If your domain and data models have a matching hierarchy and compatible interfaces, you can also consider using inheritance to derive your domain model classes from your data model classes.

    Inheritance has the advantage of less coding because you reuse your data model as your domain model, but it is at the cost of tighter coupling紧耦合. If you can ensure that you will not need to substitute a different data model and that the domain and data models will not diverge, inheritance can be effective.

    As you're writing your controller actions, you should factor complex methods into helper methods or classes in your models and services layer. Use action filter attributes such as HttpPostAttribute to avoid writing conditional logic in each action that inspects the HttpContext. Also, use action filters for cross-cutting concerns such as authentication (for example, AuthorizeAttribute) and error handling (for example, HandleErrorAttribute). Ideally, methods that handle GET should contain only a few method calls and should not contain much conditional logic; methods that handle POST should validate the incoming data, perform the update when the data is valid, and conditionally return a view depending on the success of the update. The following examples from Mileage Stats show two versions of the FillupController's Add method (first the GET version, and then the POST version). In these examples, the generic method Using<T> is a helper method used to delegate logic to the classes in the services layer.

    Skinny Controller, Fat Model

  • 相关阅读:
    软件测试
    数据库中查询json 样式的值的sql语句
    xml转json的方法
    将数据保存本地文件
    Spring 配置 web.xml (防止spring 内存溢出)
    解决maven工程 子工程中的一些配置读取进来的问题
    quartz 的简单使用
    mock 测试 MVC
    sun 证书问题解决
    将文本转换为json的工具类
  • 原文地址:https://www.cnblogs.com/chucklu/p/12523983.html
Copyright © 2011-2022 走看看