开发者

Refactoring help...property-based object or lots of member fields?

I'm currently refactoring a class which currently looks something like this:

 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.
    // ...
 }

My question is: is this really the best way to go or should I refactor all these fields into more of a property-based structure (with simply two methods setProperty and getProperty)?

Another possible refactoring would be to extract "properties" belonging together into classes of their own, such as the max/min structure into an "AllowedR开发者_StackOverflow社区ange" object or something.

Ideas?


  • You can take a look at BeanProperties - it supports constraints, events, etc.
  • Also check Project Lombok
  • You can have a Map and a bunch of constants as keys and use the setProperty to impose some of the limits. Or even to register validators.
  • If this object is supposed to be manipulated by other tools/frameworks (spring, hibernate, etc), then of course this refactoring is not an option - it should conform to the JavaBeans spec
  • ultimately, why do you need to refactor it in the first place? Isn't it doing its job well?


Of the fields you listed, I would - as you suggest - refactor minimumAllowedValue and maximumAllowedValue into a Range class, then replace them with, say, allowedRange. If I started to see that value and its allowedRange were a common pattern, I might move on to, say, a BoundedValue class. It's impossible, without seeing all the other fields, to say what to do with them, but too many fields is definitely a smell. The solution depends on their inter-relatedness, but the min & max --> range and value & range --> boundedValue examples give you some idea of the kinds of techniques to apply.

Also, keep the Single Responsibility Principle in mind.


Don't do it. It's fine.

In the future just use an IDE like Eclipse to autogenerate Javabean classes, properties and/or getters&setters in a few clicks so that you don't need to type all those code down again and again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜