[英]Is placing all setters of derived class to util class a good design?
I read some codes like this: 我读了这样的代码:
public class Base {
protected Map<String, Object> attrMap = new HashMap<>();
public Map<String, Object> getAttrMap() {
return this.attrMap;
}
}
public class DerivedA extends Base{}
public class DerivedB extends Base{}
public class Util {
public void setDerivedAAttrX(Base base, Object object) {
base.getAttrMap().put("DERIVEDA_X", object);
}
public void setDerivedAAttrY(Base base, Object object) {
base.getAttrMap().put("DERIVEDA_Y", object);
}
public void setDerivedBAttrX(Base base, Object object) {
base.getAttrMap().put("DERIVEDB_X", object);
}
public void setDerivedAttrZ(Base base, Object object) {
base.getAttrMap().put("DERIVED_Z", object);
}
}
I asked the implementor of those codes why design like this, here is his answer: 我问这些代码的实现者为什么这样设计,这是他的答案:
Base
, because it's set derived attributes. Base
,因为它设置了派生属性。 setDerivedAttrZ
.(Note that it can set attribute Z for both DerivedA
and DerivedB
)we may have a Base
reference and we will set attribute Z. We know it's DerivedA
or DerivedB
indeed, but don't know it's which one exactly. setDerivedAttrZ
。(注意它可以为DerivedA
和DerivedB
设置属性Z)我们可能有一个Base
引用,我们将设置属性Z.我们知道它的DerivedA
或DerivedB
确实,但不知道它究竟是哪一个。 So we can't cast it to derived class and call derived setters. Base
or derived class both have some shortcomings, he comes to a Util
class to handle those setters. Base
或派生类中都有一些缺点,因此他来到Util
类来处理这些setter。 So my question, is it a good design for that case? 所以我的问题是,这个案例的设计是好的吗?
I think it is bad design. 我认为这是糟糕的设计。 The basic of object-oriented programming is to call methods on objects, and not helper functions to which objects and method parameters are passed.
面向对象编程的基础是调用对象上的方法,而不是调用对象和方法参数的辅助函数。
Guess. 猜测。 This reeks of several classes having miscellaneous capabilities, some shared.
有几个具有各种功能的类,有些是共享的。 And untyped at that.
并且没有打字。
An improvement would be to use an interface with capability and use that as key. 一种改进是使用具有功能的接口并将其用作密钥。
public class Base {
private Map<Class<?>, Object> attrMap = new HashMap<>();
protected <T> void add(Class<T> clazz, T object);
/** @return null when not available. */
public <T> T lookup(Class<T> clazz) {
Object object = attrMap.get(clazz);
return clazz.cast(object);
}
}
For the lookup one could use Optional<T>
instead of a null result. 对于查找,可以使用
Optional<T>
而不是null结果。
About the original: 关于原件:
The string constants and aggregation might be too much boiler code, circumstantial coding. 字符串常量和聚合可能是太多锅炉代码,间接编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.