I have a couple of objects that I need to be able to parse with, among other things, jersey. This forces me to explicitly add an empty constructor since the frameworks are instanciating using reflection and the empty constructor.
The problem I am seeing with this is that I cannot force any preconditions. Take the following code as an example:
public class Model {
/**
* 0 < value < 100
*/
int value;
public Model() {} //The much needed empty constructor
public Model(int value) {
if(value < 1 || value > 99)
throw new IllegalArgumentException("Value must be between 1 and 99 inclusive");
this.value = value;
}
}
Here the value does have a precondition and depending on usage it might not make sense to set this to any default value(for example if value is an ID that must exist in a database). However since the other frameworks need an empty constructor, it is possible to create a Model
object that breaks the precondition and therefore is invalid.
So I am a bit curious as to how this is usually solved. Is there a way to have the empty constructor only open for reflection calls? Or is it more standard to accept that it is wrong and create a isValid
function in it that you can call to make sure that the preconditions hold? or perhaps have a different validator object that checks its validity(to keep the model clear from business logic)?