I need to modify the data members of a class, but since there are a lot of use cases, I would like to put the modifier methods in separate classes to not make the main class too large.
I think it's a good idea to extract the modification logic outside the class that defines the members. It sounds like your data members are a model and the modification logic is probably business logic. Please correct me if I'm wrong.
So I'm thinking of making the data members protected, and using derived classes as interfaces to modify the data members for each different use case. Is this a common solution to my problem? Is this a good way of solving it?
I've never seen something like this before, and it doesn't sound like good design to me. Here are the reasons:
is there something better?
I would take a different approach. I would make the model class immutable:
class Foo {
private final Integer a;
private final String b;
public Foo(Integer a, String b) {
this.a = a;
this.b = b;
}
public Integer getA() { return a; }
public String getB() { return b; }
}
Now that I have a model, I want to transform it. I can define a model transformation:
interface FooTransformation {
Foo transform(Foo foo);
}
You can now express all your use cases in terms of FooTransformation
implementations like so:
class UseCase1 implements FooTransformation {
public Foo transform(Foo foo) {
return new Foo(foo.getA() + 5, foo.getB() + "world");
}
}
This design has some good things:
- Immutable model
- Easy to unit test use cases