I have 3 methods in which i do validations in most inner method. I want to know if the validations failed or not and error message if validations failed. i know i can do something like below using exceptions to pass the error message..
String methodA(parms){
try{
return methodB(params);
}
catch(UserDefinedRuntimeException ure){
return ure.getMessage();
}
}
String methodB(params){
try{
return methodC(params);
}
catch(UserDefinedRuntimeException ure){
throw ure;
}
catch(Exception otherException){
//handle Exception
otherException.printStackTrace();
}
}
String methodC(params){
if(params.equals("A")||params.equals("B")||params.equals("C")){
return dosomething();
}
else{
throw UserDefinedRuntimeException("invalid input :params should be in [A,B,C]");
}
}
But the problem with that is many say Exceptions are expensive to create
so I by googling i found another approach suggested in
Best way to return status flag and message from a method in Java
like below ..
class Response{
int status;
String errMsg;
}
String methodA(params){
Response response = methodB(params);
if(response.status == 1){
return "success";
}
else{
return response.errMsg;
}
}
Response methodB(params){
Response response = methodC(params);
if(response.status == 0){
return response;
}
else{
//do processing
response = new Response();
response.status =1;
return response;
}
}
Response methodC(params){
if(valid(params)){
//dosomething
Response response = new Response();
response.status =1;
return response;
}
else{
Response response = new Response();
response.status = 0;
response.errMsg = "invalid data";
return response;
}
}
but the problem is unnecessary POJO class.
Please suggest some approach to deal with the situation.
Thanks In Advance.