我目前正在重构一个目前看起来像这样的类:
class SomeModel {
private String displayName;
private int id;
private boolean editable;
private int minimumAllowedValue;
private int maximumAllowedValue;
private int value;
// etc. etc.... a bunch (10+) of other fields...
// and then tons of setters and getters for these fields, some of the
// setters have restrictions depending on other settings, like you can't
// set the maximum lower than the minimum, etc.
// ...
}
我的问题是:这真的是最好的方法,还是应该将所有这些字段重构为更多基于属性的结构(只需要两个方法setProperty和getProperty)?
另一种可能的重构是将属性一起提取到属于自己的类中,例如将max / min结构提取到“AllowedRange”对象中。
想法?
答案 0 :(得分:2)
Map
和一堆常量作为键,并使用setProperty
强加一些限制。甚至可以注册验证人。答案 1 :(得分:2)
在您列出的字段中,我会 - 按照您的建议 - 将minimumAllowedValue
和maximumAllowedValue
重构为Range类,然后将其替换为allowedRange
。如果我开始看到value
及其allowedRange
是一种常见模式,我可能会继续使用BoundedValue类。如果没有看到所有其他领域,就不可能说出如何处理它们,但太多的领域绝对是一种气味。解决方案取决于它们之间的相互关联性,但是最小和最小。最大 - >范围和价值&范围 - > boundedValue示例可以让您了解要应用的技术类型。
答案 2 :(得分:1)
不要这样做。没关系。
将来只需使用像Eclipse这样的IDE,只需点击几下即可自动生成Javabean类,属性和/或getter& setter,这样您就不需要一次又一次地键入所有这些代码。