数据传输对象中的公共字段 [英] Public fields in a Data Transfer Object

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

问题描述

在我多年的编程中,我经常创建一些类,只需将一些变量与setter和getter组合在一起。我已经看到这些类型的对象被称为值对象,域对象或模型对象,具体取决于它们使用它们的上下文。通用用法的最合适的术语似乎是数据传输对象(DTO)。这描述了一个只包含访问器和变换器的POJO。

In my years of programming I've often made classes that simply group a few variables with their setters and getters. I've seen these types of objects referred to as value objects, domain objects or model objects depending on the context in which they are used. The most fitting term for generic usage seems to be Data Transfer Object (DTO). This describes a POJO that only contains accessors and mutators.

我刚刚编写了一个这样的对象,其中包含大约50个用于在图表上设置主题参数的字段。现在我想知道如果不是生成一百个getter和setter,我应该将这些字段声明为public。这样做违背了我的编程本能告诉我的一切,但我不能否认它会大大增加我的代码的易读性并减少类中样板代码的数量。

I've just written one such object that contains about fifty fields used to set theme parameters on a chart. Now I'm wondering if instead of generating a hundred getters and setters I should just declare these fields as public. Doing so goes against everything my programming instincts tell me yet I can't deny that it would greatly increase my code's legibility and reduce the amount of boilerplate code in the class.

我可以看到使用公共字段的唯一原因是我需要对这些字段执行任何类型的验证。如果我们假设类型验证足以满足我的目的,那么在这种情况下使用公共字段是否可以接受面向对象设计?公共DTO在大批量操作中表现更好吗?

The only reason I can see not to use public fields would be if I needed to perform any sort of validation on these fields. If we assume that type validation is sufficient for my purposes, is using public fields in this scenario an acceptable break from object-oriented design? Will a public DTO perform better in large batch operations?

推荐答案

大多数程序员默认使用getter / setter私有字段而不考虑它。但是像任何货物崇拜的东西一样,最好做出有意识的决定。

Most programmers will default to private fields with getters/setters without thinking about it. But like any cargo-cult thing, it's better to make a conscious decision.

使用getter / setter组合而不是公共领域的主要原因是你可以改变定义。因此,如果您的DTO是组件之间接口的一部分,那么最好使用getter。如果更改内部工作,则可以调整getter以模仿旧行为并保持兼容性。

The main reason for using a getter/setter combination instead of a public field is that you can change the definition. So, if your DTO is part of an interface between components, best to use getters. If you change the inner workings, you can adapt the getter to mimic the old behaviour and maintain compatibility.

另一个原因是您可以创建只读字段。通常对于DTO来说,只读和不可变是一个不错的选择。

Another reason is that you can make read-only fields. Often for DTOs, read-only and immutable is a good choice.

第三个原因可能是你的DTO需要是一个javabean,因为你打算在某些地方使用它需要它的工具。

A third reason could be that your DTO needs to be a javabean because you intend to use it in some tool that requires it.

如果这些属性都不适合你,则没有理由不使用公共字段。

If none of these properties go for you, there's no reason not to use public fields.

不要期望有太大的性能差异:)

Don't expect much of a performance difference though :)

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

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