Do I need protective copies for Java enumeration types?

You need to return the so-called "protective copies" of private reference types. To avoid returning a private field link.

I would like to know if this is necessary for private enumeration types. I read somewhere that enumerations are immutable reference types, so the answer should be no. Is it correct?

+6
source share
1 answer

Enumerations are not inherently immutable - but you still cannot create a protective copy, since there is only a fixed set of instances - you will need to return a link to one of the existing instances than creating a new instance.

Enumerations usually should be immutable anyway, but to counter claims that they are inherently immutable:

enum BadEnum { INSTANCE; private int foo; private int getFoo() { return foo; } public int setFoo(int foo) { this.foo = foo; } } class Test { public static void main(String[] args) { BadEnum.INSTANCE.setFoo(10); System.out.println(BadEnum.INSTANCE.getFoo()); // Prints 10 } } 

Shortly speaking:

  • Make your variables immutable. I can’t remember ever even wanting to create a volatile enumeration.
  • You cannot and should not attempt to create protective copies.
+14
source

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


All Articles