数据传输对象DTO生成位置 [英] Data Transfer Object DTO Where to build

查看:161
本文介绍了数据传输对象DTO生成位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图重构一些代码。我看到一些类创建了DTO对象,这些对象正在服务层中传递,并在以后由@RestController返回。据我所知,最好仅在控制器中构建数据传输对象并将其传递给视图,尤其是当我们使用带有get和set的 WrapperDTO< T> 之类的东西时值。当我们使用复杂的对象或简单的数据类型构建WrapperDTO时,可能会有所不同。所有意见将不胜感激。

Trying to refactor some code. I see some classes creating DTO objects which are being passes in the service layer and returned later by the @RestController. As I know it is best to build the Data Transfer Objects only in the controllers and pass them to the views, especially when we use something like WrapperDTO<T> with get and set value. Maybe there are differences when we are building the WrapperDTO with complex object or simple data types. All oppinions will be well appreciated.

推荐答案

DTO可用于在应用程序的不同层之间传递数据:DAO,Service,Facade,Controller。以我的经验,DTO是一个自以为是的话题。

DTO may be used to transfert data between the different layers of an application: DAO, Service, Facade, Controller. In my experience DTO is an opinionated topic.

在我看来,转换越晚越好,如果不需要转换,那就更好。通常,后者位于应用程序边界。 DTO不是免费的,它涉及映射及其支持。因此,当跨边界存在域模型不匹配或模型技术不匹配时,DTO将有意义。有关更多信息,请参见 LocalDTO文章和相关链接

In my opinion, the later the conversion, the better, it is even better if no conversion is needed. Generally, the later is at the application boundary. DTO is not free, it involves mapping and its support. Hence DTOs will make sense when there is a domain model mismatch or a model technical mismatch accross the boundary. For more information you can have a look at LocalDTO article and the associated link.

如果我专注于 service -> facade -> controller 层:

If I focus on the service -> facade -> controller layers:


  • 服务:他们在做服务,可能会互相调用来进行处理。如果您的域模型在服务边界上保持一致 service =>

  • Services: They are doing services things and they may call each other to do their processing. If your domain models remain consistent across the services boundary service => facade it is too early to convert the result into a DTO.

外观:他们可能会编排服务并转换输入/输出。以我的观点,这将是与DTO相互转换的正确地方。但是只有在需要的时候。因为您的域模型必须跨越此边界进行转换(过滤字段,聚合...)

Facades: They may orchestrate services and convert input/output. In my point of view it will be the right place to convert to or from DTO. But only if it is needed to ie. because your domain models have to be transformed accross this boundary (filtering fields, aggregation...)

网关/控制器:在应用程序边界。它们的逻辑很简单,简化为边界逻辑。外观与控制器之间的关系通常为 one<->。一个。 ***

Gateway/Controllers: They are at the application boundary. Their logics are simple, reduced to the boundary logic. The relation between a facade and a controller is usually one <-> one. ***

合并外观和控制器通常很有意义

Merging facades and controllers usually make sense

因此,在我看来,您的第一个建议更适合。 UserController .... 。最重要的是保持务实。

Thus in my point of view, your first proposal is more adapted eg. UserController..... The most important is to stay pragmatic.

这篇关于数据传输对象DTO生成位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆