gpt4 book ai didi

java - 实体对象应该执行代码吗?

转载 作者:搜寻专家 更新时间:2023-10-30 23:42:53 24 4
gpt4 key购买 nike

数据库的实体对象应该在其中执行代码吗?因为我听到周围人的回答不一。有些人告诉我是否应该只包含您设置的字段,而其他人则说您可以在其中做任何您想做的事情。

我在下面写了一个例子,所以你知道我的意思(假设我有所有适当的 try catch 和抛出:

@Entity
public class Man {

private Long id;
private final String name;
private final double height;
private final double weight;
private final double bmi;

public Man(String name) {

ManData data = new ManData(name);

this.name = name;
this.height = data.getHeight;
this.weight = data.getWeight;
this.bmi = BMI.calculate(height, weight);

}

}

1) 假装 ManData 对象从互联网获取信息。2) bmi 也是从接收到的数据中计算出来的,不是通过传递的。

在 Entities 中做这种事情可以吗?

最佳答案

长答案:

Martin Fowler 在此处发表了一篇关于贫血域的精彩博文:http://www.martinfowler.com/bliki/AnemicDomainModel.html

他将它们定义为:

The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.

tl;dr

是的,在您的域对象中添加比 getter 和 setter 更多的代码是可以的。

编辑以修复拼写

关于java - 实体对象应该执行代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32923565/

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