Java - 如何只创建具有有效属性的对象? [英] Java - How to only create an object with valid attributes?

查看:151
本文介绍了Java - 如何只创建具有有效属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个基本的Java课程,我遇到了一个问题:如果我已经将有效参数传递给构造函数,我该如何创建一个对象?

I'm doing a basic Java course and I came to a problem: How do I create an object only if I have passed valid parameters to the Constructor?

在实现验证后,我应该创建一个替代类并从那里调用构造函数吗?

Should I make an alternate class and call the constructor from there after the validation is realized?

或者我应该/可以在课堂上使用静态方法进行验证吗?

Or should/could I use a static method in the class for the validation?

这种情况下的最佳做法是什么?

What is the best practice in this case?

推荐答案

标准做法是验证构造函数中的参数。例如:

The standard practice is to validate the arguments in the constructor. For example:

class Range {
  private final int low, high;
  Range(int low, int high) {
    if (low > high) throw new IllegalArgumentException("low can't be greater than high");
    this.low = low;
    this.high = high;
  }
}

附注:验证参数不为空,这是相当常见的,您可以使用:

Side note: to verify that arguments are not null, which is fairly common, you can use:

import static java.util.Objects.requireNonNull;

Constructor(Object o) {
  this.o = requireNonNull(o); //throws a NullPointerException if 'o' is null
}






更新


UPDATE

回复您对社会安全号码的具体评论。一种方法是向类中添加一个方法:

To reply to your specific comment about social security number. One way would be to add a method to the class:

//constructor
public YourClass(String ssn) {
  if (!isValidSSN(ssn)) throw new IllegalArgumentException("not a valid SSN: " + ssn);
  this.ssn = ssn;
}

public static boolean isValidSSN(String ssn) {
  //do some validation logic
}

调用代码可能如下所示:

The calling code could then look like:

String ssn = getSsnFromUser();
while(!YourClass.isValidSSN(ssn)) {
  showErrorMessage("Not a valid ssn: " + ssn);
  ssn = getSsnFromUser();
}
//at this point, the SSN is valid:
YourClass yc = new YourClass(ssn);

通过这种设计,你实现了两件事:

With that design, you have achieved two things:


  • 您在使用之前验证了用户输入(您应该始终这样做 - 用户非常擅长拼写错误)

  • 您已确定如果 YourClass 被滥用引发异常并且它将帮助您检测错误

  • you validate the user input before using it (which you should always do - users are very good at typos)
  • you have made sure that if YourClass is misused an exception is thrown and it will help you detect bugs

你可以通过创建一个包含SSN并封装验证逻辑的 SSN 类来进一步发展。 YourClass 然后接受一个 SSN 对象作为参数,它始终是一个有效的SSN构造。

You could go further by creating a SSN class that holds the SSN and encapsulates the validation logic. YourClass would then accept a SSN object as an argument which is always a valid SSN by construction.

这篇关于Java - 如何只创建具有有效属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆