views:

63

answers:

3

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 "AllowedRange" object or something.

Ideas?

+2  A: 
  • 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?
Bozho
+1  A: 

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.

BalusC
Don't let your IDE generate code. OK, you don't have to type it, but you still have to read it. And it is hard to find the one method you modified beween all those methods that are simply boiler plate.
Roel Spilker
@Roel Spilker: just hide them away deep in bottom of your class and make use of `Ctrl+O` to find them.
BalusC
+2  A: 

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.

Carl Manaster