gpt4 book ai didi

java - DDD 中域类的 getter 不应以 "get"为前缀,为什么?

转载 作者:行者123 更新时间:2023-12-02 06:18:45 26 4
gpt4 key购买 nike

DDDSample project ,现在托管在 Github repository ,好像是一个关于如何设计DDD项目的引用。

我注意到域类中的所有 getter 都没有以 get 为前缀(例如:Cargo#delivery),而它们在域包外部的类中都有前缀(例如:HandlingEventRegistrationAttempt#getTrackingId)。

Richard C. Martin 在他的《Clean Code》一书中指出:

Accessors, mutators, and predicates should be named for their value and prefixed with get, set, and is according to the javabean standard.

那么,在这种情况下我们应该避免听从他的建议吗?如果是这样,为什么它比一致性更重要?

最佳答案

Why getters from domain classes should not be prefixed with “get” in DDD?

最简单的起点是更改器(mutator);请注意干净代码

中的前一句

Mutators should have verbs or verb phrase names like postPayment, deletePage, or save.

这个想法与领域模型不应该贫乏、领域语言应该普遍存在的原则是一致的:我们应该在我们的领域的代码中看到相同的语言专家在解释业务时使用。

这就是为什么您不会经常看到set,除非该动词碰巧在您的领域中具有重要意义。

访问器和谓词都是查询的示例。正如 Bertrand Meyer 所理解的,查询在不修改实例的情况下提供有关实例的信息,并且它们满足统一访问原则

from the outside, whether a query is an attribute (field in each object) or a function (algorithm) should not make any difference. For example a_vehicle.speed could be an attribute, accessed from the object's representation; or it could be computed by a function that divides distance by time. The notation is the same in both cases, so that it's easy to change representation without affecting the rest of the software.

那么,这些应该如何命名?

沃恩·弗农,在 Implementing Domain-Driven Design ,写道

The method names of Side-Effect-Free Functions are important. Although these methods all return Values (because they are CQS query methods) they purposely avoid the use of the get-prefix JavaBean naming convention. This simple but effective approach to object design keeps the Value Object faithful to the Ubiquitous Language. The use of getValuePercentage() is a technical computer statement, but valuePercentage() is a fluent human-readable language expression.

史蒂文·洛写道

Developers tend to think and talk in development terms, which naturally results in inadvertent models of how instead of what and why. This is common, and it's a tar pit, because developers tend to follow established patterns. What's more, once the true purpose of the code is obscured, it's unlikely that anyone will unearth it.

我会这样表达这个想法:领域专家应该能够阅读领域模型中的代码,并评估其正确性。这意味着域代码不应嵌入与基础设施相关的工件。

罗伯特·马丁对这个想法的拼写?

Reader's shouldn't have to mentally translate your names into other names they know.

(马丁后来断言,术语应该取自解决方案领域,前提是大多数读者都是程序员,而不是领域专家。DDD 的反驳观点是,程序员应该在建模时获取领域专业知识业务。)

关于java - DDD 中域类的 getter 不应以 "get"为前缀,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46139501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com