我目前正在重构一个目前看起来像这样的类:
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)?
另一种可能的重构是将属于一起的“属性”提取到它们自己的类中,例如将最大/最小结构提取到“AllowedRange”对象或其他东西中。
想法?
最佳答案
- 你可以看看BeanProperties - 它支持约束、事件等。
- 同时检查 Project Lombok
- 您可以将一个
Map
和一组常量作为键,并使用setProperty
来施加一些限制。甚至注册 validator 。 - 如果该对象应该由其他工具/框架(spring、hibernate 等)操作,那么当然不能进行重构 - 它应该符合 JavaBeans 规范
- 最后,您为什么首先需要重构它?它的工作做得不好吗?
关于java - 重构帮助...基于属性的对象或大量成员字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2056089/