Java imposes ultimate software

What is the correct way to ensure the value is set only once, although its installation time is unknown (i.e. not in the constructor). I could do a null check or track the flag and throw an exception - but what exception should I do? This is for a small localized library, and I prefer not to create my own ValueAlreadyAssigned exception for this seemingly common case.

+4
source share
3 answers

The method may throw an IllegalStateException , as javadocs says:

Signals that the method was called at an unacceptable unacceptable time.

+4
source

In the setter. Do it like this:

 private foo bar; public void setFoo(foo bar) { if (this.bar == null) { this.bar = bar; } else { System.out.println("Don't touch me!"); // J/K Throw an IllegalStateException as Michal Borek said in his answer. } } 
+8
source

Defining your own IMHO exception is not a big deal, especially if it extends a RuntimeException . Therefore, I suggest you define a ValueAlreadySetException extends IllegalStateException and use it.

The next point is the logic in each setter, which you should duplicate as suggested by @Renan. I offer you the following. Define a special generic container and use it:

 public class SetOnceContainer<T> { private Class<T> type; private String name; private T value; private boolean set = false; public SetOnceContainer(Class<T> type, String name) { this.type = type; this.name = name; } public void set(T value) { if (set) { throw new ValueAlreadySetException(name); } this.value = value; this.set = true; } public T get() { return value; } } 

Note that this implementation supports null values.

Now you can use it as:

 public MyClass { private SetOnceContainer<Integer> number = new SetOnceContainer<Integer>(Integer.class, "number"); private SetOnceContainer<String> text = new SetOnceContainer<String>(String.class, "text"); public void setNumber(int value) { number.set(value); } public void setText(String value) { text.set(value); } public Integer getNumber() { return number.get(); } public String getText() { text.get(); } } 

Implementation is encapsulated at one time. You can change it in one place if you need. Null values ​​are also supported. Settings and getters are a bit more complicated than regular ones.

+1
source

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


All Articles