gpt4 book ai didi

java - 公开类等数据结构中的成员?

转载 作者:行者123 更新时间:2023-11-30 07:38:22 25 4
gpt4 key购买 nike

为了在基于 Servlet 的应用程序中使用,我编写了一个类来存储 View 名称和要呈现的对象。实际上,在 OOP 的意义上,它更像是一种数据结构,而不是类。我想知道我是否应该公开成员,或者是否应该使用 getter。

public class Result {

private final int status;
private final String view;
private final Map<String, Object> model = new HashMap<String, Object>();

public Result(final int status, final String view) {
this.status = status;
this.view = view;
}

public Result put(final String modelName, final Object modelObject) {
model.put(modelName, modelObject);
return this;
}

}

我应该添加 getStatus()、getView() 和 getModel() 还是应该将成员可见性更改为“公开”?目前我不知道在任何情况下使用访问成员的方法会有用。 “结果”是一个不可变的数据结构,访问成员时不需要计算。您是否会为实现更改这种不太可能发生的事件添加 getter?

附录

我在 Robert C. Martin 的优秀著作 Clean Code 中阅读了与我的问题相关的部分(第 99 页):

Hybrids

This confusion [about objects and data structures] sometimes lead to unfortunate hybrid structures that are half object and half data structure. They have functions that do significant things, and they also have either public variables or public accessors and mutators that, for all intents and purposes, make the private variable public, tempting other external functions to use those variables the way a procedural program would use a data structure.

Such hybrids make it hard to add new functions but also make it hard to add new data structures. They are the worst of both worlds. Avoid creating them. They are indicative of muddled design whose authors are unsure of - or worse, ignorant of - whether they need protection from functions or types.

最佳答案

对于数据持有者类,是否创建 getter 是个人喜好问题。根据您的描述,您可以将可见性公开或打包状态和 View ,但我会添加一个 getter 来按名称检索模型。虽然 map 是最终的,但它的内容不是。

编辑我的意思是:

public Object get(final String modelName) {
return model.get(modelName);
}

没有理由让模型图可见。 (我会将 map 命名为“models”并使用 setModel(name, model)getModel(name) 作为访问器。)

关于java - 公开类等数据结构中的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1991475/

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