如何验证其他类别构建的请求?

发布于 2025-01-22 04:31:30 字数 1221 浏览 0 评论 0原文

有一个类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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文