The below idea seemed to look clean, to allow the object itself to validate its values for different scenarios.
For eg:
- While creating the object, the value of Object1 and Object2 in SelfValidator object should be validated for not null.
- At one scenario like inserting the SelfValidator object to Database, validation of value1 as non-zero has to be done, which is not necessary for an Update. A new validate function: validateForInsert(), which will validate and set the error data, can be included to SelfValidator class.
But I am sure, there might be some drawbacks, design flaws, which I would like to understand and improve.
ErrorInfo.java
public class ErrorInfo {
String errorMessage = "";
public void setErrorMessage(String errorMessage) {
this.errorMessage = new StringBuffer(this.errorMessage).append("\n+").append(errorMessage).toString();
}
}
SelfValidator.java
public class SelfValidator {
String object1;
String object2;
int value1;
ErrorInfo errorInfo;
public ErrorInfo getErrorInfo() {
return errorInfo;
}
public SelfValidator(String object1, String object2, int value1) {
super();
this.object1 = (object1 == "")?null: object1;
validate(this.object1, "object1");
this.object2 = (object2 == "")?null: object2;
validate(this.object2, "object2");
this.value1 = value1;
}
private void validate(String value, String dataMember) {
if(value == null){
if(errorInfo == null){
errorInfo = new ErrorInfo();
}
errorInfo.setErrorMessage(dataMember +" value is invalid");
}
}
}
Demonstrator.java
public class Demostrator {
public static void printValidOrNot(ErrorInfo errorInfo){
if(errorInfo == null){
System.out.println("Object valid");
//Proceed with manipulating the object
}else{
System.out.println(errorInfo.errorMessage);
// Break and handle the error.
}
}
public static void main(String[] args) {
SelfValidator selfValidatingObject1 = new SelfValidator("Test", "Test", 1);
printValidOrNot(selfValidatingObject1.getErrorInfo());
SelfValidator selfValidatingObject2 = new SelfValidator("", "", 1);
printValidOrNot(selfValidatingObject2.getErrorInfo());
}
}