I have the following class:
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.
}
}
Similarly I can do the same as follows:
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.
}
}
For Testing which one is more preferable? Can i say that the second UserValidator class has a state and thus easier to test, whereas first one doesnt have a state and harder to test? Matter of the fact the first one can be a static class as well, which can not be passed to other methods, but if called statically it doest work.
Which one is better in terms of testability? which one contains state? which is more ideal?
Only the second one contains state.
Personally, I would use the first one statically, like
However, there is an advantage to storing the result – you can run it again and again without needing to actually run it.
To have a list of various validators, you will need some kind of interface to perform that.
Then you would create a static method library with all your validation. Note that these are made up examples, but contain some real-world-ish kind of logic.
Later if you need multiple validators, you can simply do this
Then when you get a request, you simply do this to validate it: