(主观)无效的Java类构造函数

huangapple go评论81阅读模式
英文:

(Subjective) Invalid Java Class Constructor

问题

我正在编写一个Java类,其中给定的参数可能无效,但仍然是正确的类型。我希望我的类接受两个整数,但不允许第二个整数为零。我有哪些可能性来中断构造函数,也许手动返回null?我的可能性有哪些?

public class Test {
   private int a, b;
   public Test(int p1, int p2) {
       if (p2 == 0) {
           // Do something to handle the invalid parameter, such as throwing an exception.
       } else {
           a = p1;
           b = p2;
       }
   }
}
英文:

I am programming a java class, where the given parameters could be invalid, but still be the right type. I want my class to take two integers, but the second one is not allowed to be zero. What do I have for possibilities to interrupt the Constructor, maybe returning manually null? What are my possibilities?

public class Test {
   private a, b;
   public Test(p1, p2) {
       if (p2 == 0) return null;
       a = p1;
       b = p2;
   }
}

答案1

得分: 2

构造函数没有返回值因此返回 `null` 不是一个选项惯用的做法是抛出 [`IllegalArgumentException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalArgumentException.html):

```java
public class Test {
   private a, b;
   public Test(p1, p2) {
       if (p2 == 0) {
           throw new IllegalArgumentException("p2 不能为零");
       }
       a = p1;
       b = p2;
   }
}
英文:

A constructor doesn't have a return value, so returning null isn't an option. The idiomatic thing to do would be to throw an IllegalArgumentException:

public class Test {
   private a, b;
   public Test(p1, p2) {
       if (p2 == 0) {
           throw new IllegalArgumentException("p2 can't be null");
       }
       a = p1;
       b = p2;
   }
}

答案2

得分: 2

如果您想在参数无效的情况下返回 null,不能使用构造函数。

相反,将构造函数设置为私有,并编写一个静态工厂方法:

private Test(int a, int b) {
  // 任何操作。
}

public static Test create(int a, int b) {
  if (/* a 和 b 无效 */) {
    return null;
  }
  return new Test(a, b);
}

然后,您应该调用 Test.create 而不是 new Test

但前提是您不打算扩展 Test

英文:

If you want to return null in the case of invalid parameters, you can't use a constructor.

Instead, make the constructor private, and write a static factory method:

private Test(int a, int b) {
  // Whatever.
}

public static Test create(int a, int b) {
  if (/* a and b are invalid */) {
    return null;
  }
  return new Test(a, b);
}

You then invoke Test.create instead of new Test.

This is only an option if you don't want to extend Test, though.

答案3

得分: 0

根据您的需要,有很多可能性,这是最重要的事情。

一个想法可能是,如果第二个参数为0,就抛出IllegalArgumentException异常,这样构造函数会以错误退出,而类不会被创建。

英文:

Quite a lot of possibilities, depending on what you need, which is the most important thing.

An idea could be throw an IllegalArgumentException if the 2nd parameter is 0 so the constructor exits with error and the class is not created.

huangapple
  • 本文由 发表于 2020年8月31日 02:37:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63660899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定