I have a class with lots of fields. They should basically be set at the constructor phase and never change. Semantically the class then is an immutable one.
public class A{
final int a;
final short b;
final double e;
final String f;
final String g;
//and more
}
The problem is that normally these fields have default values and therefore I do not want to always burden the user with a constructor with all of them. Most time, they just need to set a couple of them. There are a couple of ways to solve this:
- I would need lots of constructor with different signature.
- Create a bunch of set method of these field and only set those non-default value. But this somehow indicate a different semantics other than immutable nature.
- Create a new parameter class that is mutable and use that class as constructor.
None of that is totally satisfactory. Is there any other approach? Thanks.
One way
I would use a combination of a parameter class and a fluent builder API for creating the parameter:
Then create instances of A like this:
Class A is immutable, the parameters are optional, and the interface is fluent.