How to create a semantically immutable object with many fields

I have an object with 25 fields. It has no logic, just keep the values. It is built with an abstract builder. I do not want something to change this object after assembly. I want all fields to be final, but I don't want to create a 25-params constructor. What model should be used in this situation? Now I'm thinking of local setter packages, but this is worse than syntax checking for all the values โ€‹โ€‹given in the final fields. I canโ€™t pack these fields into 2-3 objects

+4
source share
2 answers

I see three main options:

  • Have a private class that only the builder knows about, and an open interface with only getters. The builder issues links using an interface, not a class.

  • You have two classes: one modified (which is part of the Messenger class) and one that is immutable, which accepts the changed in its constructor and captures its fields.

  • The class has reasonable default values โ€‹โ€‹for all fields, and then there are setters that return a new instance of the class with this set of fields. The disadvantage here is that to create a 25-field instance, you create ~ 24 drop objects, depending on how many reasonable default values โ€‹โ€‹you need to change .; -)

+10
source

Assign the Builder class as a static nested class in the Entity class. Then the Builder class can set fields directly, and you donโ€™t need the configuration methods or the n-arg constructor in Entity .

 public class Entity { // Just one attribute and getter here; could be 25. private int data; public int getData() { return data; } public static class Builder { // Just one attribute and getter here; could be 25. private int theData; public Entity build() { Entity entity = new Entity(); // Set private field(s) here. entity.data = theData; return entity; } public Builder setData(int someData) { theData = someData; return this; } } } 

Using:

 Entity entity = new Entity.Builder().setData(42).build(); 
+8
source

Source: https://habr.com/ru/post/1502659/


All Articles