1

I can write my own but I'm guessing this is very standard. Is there a standard java class that does this? I know this has to be a runtime feature because various parts of my code could set it without knowing what each other are doing - I just want this to fail loudly if this happens.

public class MutableOnce<Type T> { private T _t; private boolean _isSet = false; public void set(T t) { if(_isSet) { //raise exception } _t = t; public T get() { return _t; } } 

2 Answers 2

6

Any reasons why you don't want to simply make the object immutable? It would make the class much easier to use, especially in a concurrent environment (the class in your example is not thread safe).

public class Immutable<T> { private final T _t; public void Immutable(T t) { _t = t; } public T get() { return _t; } //you may want to return a copy of _t if _t is mutable } 
Sign up to request clarification or add additional context in comments.

4 Comments

Other requirement is that the boolean I'll be wrapping is false by default, which means it has to exist before it's set - which is why an immutable w/ constructor as setter won't work. I could perhaps make it nullable and if(isNull) treat it as false... looking for a simple design that encapsulates the "setting" of this boolean.
Why don't you create the object when you need it? Before it is created it does not exist... Not sure what you are trying to achieve with this structure. It would help if you could explain why you need that behavior.
That would be the nullable design. Rather than "have" one I will need to create a place to store it and maintain logic to check whether I have one already. Given that the default value is false I can avoid this and just have one from the start that can only be overridden once. Sounds like I just have to make up my mind, the complexity is kind of conserved in either design.
I am not sure I fully understand, but checking if object==null with an immutable design seems easier to design and maintain. If there are more than one object, you could store them in a collection as you create them and check if the collection is empty for example...
1

After a quick search:

  1. All the fields must be private and preferably final
  2. Ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
  3. Fields must be populated from the Constructor/Factory
  4. Don't provide any setters for the fields
  5. Watch out for collections. Use Collections.unmodifiable*. Also, collections should contain only immutable Objects
  6. All the getters must provide immutable objects or use defensive copying
  7. Don't provide any methods that change the internal state of the Object.

Source: Possible ways of making an Object immutable

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.