gpt4 book ai didi

java - 重构帮助...基于属性的对象或大量成员字段?

转载 作者:行者123 更新时间:2023-11-29 08:18:49 24 4
gpt4 key购买 nike

我目前正在重构一个目前看起来像这样的类:

 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/

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