1

I have got an interview question where interviewer asked me, "How will you create an immutable class in java, which class will have more than 100 fields in it?"

As we know to create immutable class we need to declare a class as final, need to declare all the fields as final and there should not be any setter method present in that class. We need to initialize those field in the constructor.

But what will happen when we have more than 10 fields or more fields? We can not pass all the fields in the constructor right? In this scenario, how can we create an immutable class?

Arghya Pal
  • 15
  • 7
  • 6
    Builder design pattern should solve your problem. – hvaminion Jun 14 '19 at 12:45
  • 1
    10 constructor parameters are too many! https://stackoverflow.com/questions/40264/how-many-constructor-arguments-is-too-many you should not hava a class with 100 fields in it. should have given this as the first answer. – bucky Jun 14 '19 at 12:46
  • this library can make any object immutable : https://github.com/verhas/immutator – Mustahsan Jun 14 '19 at 12:48
  • @bucky It was just an example (10 parameters in the constructor) you can think of it as 20 or 30 or more. However, as per the sonar standard, what I know is constructor should not have more than 7 parameters. – Arghya Pal Jun 14 '19 at 12:51

1 Answers1

3

The field count here is irrelevant, even if having more than a few fields in one class is horrible design and is a sign the class should be refactored. To make a class immutable, you need the following:

  1. No setter methods. this means you either want a Builder inner class which sets the values of your fields before calling the constructor, or simply include all fields as constructor parameters (highly recommended against).
  2. Declare the class as final. This prevents classes from extending and calling super.
  3. If you have non-primitive fields inside your immutable class, you'll need to copy them and return the copy each time you make a change to them.

Btw, as far as I'm aware, Java constructors can handle 255 parameters. So for this interview, constructor parameters would be an option.

Austin Schaefer
  • 695
  • 5
  • 19
  • I have proposed the same thing to the interviewer but he was not satisfied. However, I was not aware of the Builder design pattern. – Arghya Pal Jun 14 '19 at 13:00