2

我有以下课程:

class UserValidator{

     // no constructor , default is fine. 

     void Validate(Request request, Response response){
        // some validation logic on request
        // if fails, add the message to response.
     }

}

同样,我可以执行以下操作:

class UserValidator{

     private Request request;
     private Response response;

     UserValidator(Request _request, Response _response)
     {
         request = _request;
         response = _response;
     }

     void Validate(){
        // some validation logic for request
        // if fails, add the message to response.
     }

}

对于测试,哪个更可取?我可以说第二个 UserValidator 类有一个状态,因此更容易测试,而第一个没有状态并且更难测试吗?事实上,第一个也可以是一个静态类,它不能传递给其他方法,但是如果静态调用它就不起作用。

哪一个在可测试性方面更好?哪个包含状态?哪个更理想?

4

1 回答 1

0

只有第二个包含状态。

就个人而言,我会静态使用第一个,比如

class UserValidator{

     private UserValidator() { } // no constructor

     public static void Validate(Request request, Response response){
        // some validation logic on request
        // if fails, add the message to response.
     }

}

但是,存储结果有一个优势——您可以一次又一次地运行它,而无需实际运行它。

class UserValidator {
    public static enum ValidatorState { NOT_RUN, PASSED, FAILED }
    private ValidatorState state = NOT_RUN;
    private final Request request;
    private final Response response;
    public UserValidator(Request request, Response response) {
        this.request = request;
        this.response = response;
    }
    public ValidatorState validate() {
        if(state != NOT_RUN) return state;
        if(blah blah)
            state = PASSED;
        else
            state = FAILED;
        return state;
    }
}

要获得各种验证器的列表,您将需要某种接口来执行该操作。

public interface Validator {
    boolean validate(Request request, Response response);
}

然后,您将创建一个包含所有验证的静态方法库。请注意,这些都是虚构的示例,但包含一些真实世界的逻辑。

public class ValidationLibrary {
    private ValidationLibrary() { }
    public boolean validateUsername(Request request, Response response) {
        String name = request.getProperty("username");
        if(name.length() < 3) return false;
        if(name.length() > 12) return false;
        if(name.equals(name.reverse()) return false; // who knows?
        return true;
    }
    public boolean validateSecurity(Request request, Response response) {
        // what page is the user trying to reach?
        SecurityRealm realm = SecurityRealm.realmForPage(request.getProperty("page"));
        String username = request.getProperty("name");
        return realm.allows(username);
    }
}

稍后如果您需要多个验证器,您可以简单地执行此操作

List<Validator> validators = new ArrayList<Validator>();
validators.add(new Validator(){ 
    public boolean validate(Request req, Response res) { ValidationLibrary.validateUsername(req,res); } 
});
validators.add(new Validator(){ 
    public boolean validate(Request req, Response res) { ValidationLibrary.validateSecurity(req,res); } 
});

然后,当您收到请求时,您只需执行以下操作即可对其进行验证:

for(Validator v : validators) if(!v.validate(request,response)) return false;
于 2012-08-30T21:17:54.103 回答