Reputation: 1397
In Java I have a bunch of variables (of different types) that I would like to check that they have been set before using them, and if they have not then the result is always the same and I want to throw an error that'll be caught higher up. In theory the code is designed that this should NEVER happen, but the consequences of a bug making it happen are too great to leave it to just unit testing.
I was thinking of just making a template that has a get() and set() function. The set would set the value and set a boolean to let it know it has been set and the get() would check the boolean and return the value or throw an error. something like:
Class ImportantInfo<T> {
private T t;
private beenSet = false;
public T get(){
if(beenSet) return t;
else throw error;
}
public void set(T value){
t =value;
beenSet = true;
}
}
Is this the correct and best approach? Are there other, possibly better, ways? I worry I am over engineering the solution or that a template this straightforward might already exist in Java?
Upvotes: 2
Views: 113
Reputation: 1409
One approach to do this would be to use Java Optional
s. Optional
s represent a value that may or may not be present.
Optional.empty()
represents a value that is not present.get()
method gets a value if it is presentisPresent()
checks if a value has been set or not.The main advantage of using Optional
over simply checking for null
is that optional forces you to use .get()
so you don't accidentally call a null value that hasn't been set.
In your particular case, I would initialize all the values at the top of the class to Optional.empty()
and then use .isPresent
to make sure they were set.
Note: This will only work with Java 8
(Apparently Guava Optional
will work in versions less than 8 (see Tom's comment - I have no experience with this)
Upvotes: 3
Reputation: 5423
there are many ways, but the approaches that I would normally find useful:
checking if its null
, personally I just use this, if null
I assume its not been set otherwise its been set, then you can also give the user the responsibilities (optional)
instead of having setter
method, you can use the constructor
. this way you ensure that the value has been set before even being able to use the get
method.
Upvotes: 1