如何验证其他类别构建的请求?
有一个类userRequest
class UserRequest {
private Name name;
private Address address;
private Date dob;
//getters and setters
}
此类是从其他类构建的:name
和地址
和date
。他们可能看起来
class Name {
private String first;
private String second;
//getters and setters
}
class Address {
private String street;
private String state;
private String zip;
//getters and setters
}
需要验证所有字段并返回多误响应。
public List<ErrorItem> validate(UserRequest request){
List<ErrorItem> errors = new ArrayList<>();
if(request.getName().getFirst() == null){
errors.add(new ErrorItem(...))
}
if(request.getName().getSecond() == null){
errors.add(new ErrorItem(...))
}
return errors;
}
您可以注意到可能的NPE。
一方面使用逻辑上相同的字段上方的类 - w-wrappers是最佳实践(名称:第一和第二,地址:街道,州,zip)。
在第二侧,它带来了其他检查/验证。 我不知道他该怎么说
if(request.getName() == null) {
errors.add(???)//I don't have a message or error code for that.
}
另外,如果用户将空的用户request
:我应该验证这样的案例, ?如果我应该抛出一个例外 - 我应该投掷什么例外? illigalargumentException?也许,一个简单的课堂在一个父班中都有所有字段更好?我不这么认为。那么,什么是最佳实践?
There is a class UserRequest
class UserRequest {
private Name name;
private Address address;
private Date dob;
//getters and setters
}
This class is built from other classes: Name
and Address
and Date
. they might look like
class Name {
private String first;
private String second;
//getters and setters
}
class Address {
private String street;
private String state;
private String zip;
//getters and setters
}
I need to validate all fields and return a multi-error response.
public List<ErrorItem> validate(UserRequest request){
List<ErrorItem> errors = new ArrayList<>();
if(request.getName().getFirst() == null){
errors.add(new ErrorItem(...))
}
if(request.getName().getSecond() == null){
errors.add(new ErrorItem(...))
}
return errors;
}
You can notice possible NPE.
On one side using classes-wrappers above the group of fields that are the same logically is the best practice(Name: first and second, Address: street, state, zip).
On the second side, it brings additional checks/validations. Also, I don't know what should I say to a user if he passed empty UserRequest
:
if(request.getName() == null) {
errors.add(???)//I don't have a message or error code for that.
}
Should I validate cases such as that? If I should throw an exception - what exception should I throw? IlligalArgumentException? Or maybe, a simple class with all fields in one parent class is better? I don't think so. So, what is best practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论