Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is a good practice to handle validation in java

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.

like image 422
kasinavijay Avatar asked Jan 29 '15 15:01

kasinavijay


1 Answers

the problem with that is many say Exceptions are expensive to create

Trading readability for performance is always a bad deal. CPU cycles get a lot cheaper every year, making performance effects less valuable. At the same time, human's ability to reason about programs does not get "upgraded" at all, making the negative effects of readability changes permanent. Hence you are buying a rapidly depreciating asset.

When the logic of your program requires you to report an exception, the best approach is to throw an exception. The cost is there only when you actually throw an exception, which should rarely happen.

At the same time, one should not use exceptions for non-exceptional situations (i.e. situations that you anticipate to happen regularly). End-users entering wrong data into fields is one such non-exceptional situation. When you implement something like this, the second way that you show is a proper way of doing it.

But the problem is unnecessary POJO class.

Another alternative is to switch from the "pull model" to a "push model", when methods call you back with different kinds of responses, rather than you querying responses for status. Here is a skeletal implementation of this approach:

public interface ResponseHandler {
    void validDataEntered(String data);
    void invalidDataEntered(String data);
}

public class Processor {
    void methodA(String param1, String param2, ResponseHandler h) {
        if (!param1.valid()) {
            h.invalidDataEntered(param1);
            return;
        }
        if (!param2.valid()) {
            h.invalidDataEntered(param2);
            return;
        }
        validDataEntered(param1+":"+param2);
    }
}

public class MainClass implements ResponseHandler {
    Processor p = new Processor();
    public void validDataEntered(String data) {
        System.out.println("Got valid data: "+data);
    }
    public void invalidDataEntered(String data) {
        System.err.println("Got invalid data: "+data);
    }
    public void doSomething() {
        p.methodA("one", "two", this);
    }
}
like image 50
Sergey Kalinichenko Avatar answered Oct 13 '22 09:10

Sergey Kalinichenko