0
votes

I read some lines in Effective Java: Programming Language Guide Joshua Bloch and find out that I should avoid the usage of mutable objects. Because of I read the book I know how to make a mutable object immutable (e.g. usage of private and final modifier).

Well however I have a "dummy" data holder class with some private fields. Each field is accessable with a get method and also a corresponding set method. So because of this set methods objects of this class are not immutable.

The question is now how to avoid these set methods? Pass all (e.g. 20) parameters to the object constructor? I think this is not really good design because I have to keep care of the order of parameters, have to pass null references if I do not want to set a special parameter and so on.

So I think about following approach:

  • Create an interface with all get methods and let it implement from dummy data holder class
  • Create an abstract class with a private constructor and a static factory method which returns the "get" interface instance of the data holder object.
  • In the static factory method I configure the data holder object with all necessary set methods
  • Make the data holder class package private so that a object can only be instanciated over the static factory method which is defined in the abstract class

In the next step I store the configured and created data holder objects in a list.

What is the best approach to read out a object an modify the object although it is immutable? Create a new object with a static factory method which sets the new value internally and replace it with the object in the list?

1
Check out the builder pattern. And also have in mind that immutability is not only about not having setters. Objects can also be mutated through a getter.NilsH

1 Answers

0
votes

As @NilsH pointed out: you should go for the Builder pattern, ideally based on a fluent interface.

As an example, you may look at make-it-easy.