I have a "Validator" class which allows us to set values of its member variables (mostly boolean) - mv1, mv2, mv3 etc. with setter methods. Lets call all these variables "settings". All the setter methods return this Validator instead of the usual void.
The Validator has a validate(Input input) method which takes an "Input" object and validates it based on the values of settings of Validator. There are some dependencies between the various settings. For example, if mv1 = true, then mv3 cannot be true etc. Also, I cannot always use enums to restrict the values of the settings !
I validate all the inputs with validateInputs(). The validate(Input input) calls it before doing the validation. I want to find out all the invalid inputs, display them all at once and then prevent the validation until the inputs are fixed. What is the best way to do this in Java ?
What did I try ?
I don't want to throw an IllegalArgumentException right after I find the 1st setting with invalid value. I want to avoid writing custom code which will handle these exceptions and then list them all at once. I also don't want to use Java's assert because it can be disabled at run time.
To solve my problem, I simply use TestNg library's SoftAssert to validate the member variables. The code inspects some of the the member variables, asserts that the variables have valid values and finally does softAssert.assertAll() to list all the wrong values at once. But, I wonder if Java has any in-built features to do this.
class Validator {
//Validator settings
boolean mv1;
boolean mv2;
MyEnum mv3;
boolean mv4;...etc.
//Setters - One example.
public Validator setMv1(boolean ){
this.mv1 = mv1;
return this;
}
//Validation logic
public void validate(Input input){
validateSettings();
//Now, validate the input.
}
//Validate the settings of this Validator.
private void validateSettings(){
SoftAssert assertz = new SoftAssert();//From TestNg library.
//No need to validate all settings ! Only some needed.
//Assert that if mv1 = true, then mv3 can't be true;
//Assert other things.
assertz.assertAll();
}
}
Aucun commentaire:
Enregistrer un commentaire