简体   繁体   English

Java 接口模式和 RuntimeExceptions

[英]Java pattern for interfaces and RuntimeExceptions

I am using the following pattern in a project of mine.我在我的项目中使用以下模式。

public interface Foo {
  // When given a positive number, double it
  public Integer doublePositiveNumber(int number);
}
public class FooImpl {
  public Integer doublePositiveNumber(int number) {
    if (number < 0) {
      throw new IllegalArgumentException("number must be positive")
    }
    return number * 2;
  }
}

There is one main thing that has been bothering me about this design.关于这个设计,有一个主要问题一直困扰着我。 It's not clear to anyone using this implementation of the interface that they may need to handle an IllegalArgumentException.使用此接口实现的任何人都不清楚他们可能需要处理 IllegalArgumentException。 Likewise, I want other implementations of this interface to throw this exception if a negative number is passed in.同样,如果传入负数,我希望此接口的其他实现抛出此异常。

I've thought about a few approaches to solving this:我想过几种方法来解决这个问题:

1) Do nothing, this pattern is fine and normal 1)什么都不做,这个模式很好很正常

2) Throw a custom checked exception instead. 2)改为抛出自定义检查的异常。 This feels awkward since IllegalArgumentException is perfect for this error.这感觉很尴尬,因为 IllegalArgumentException 非常适合这个错误。

3) Add "throws IllegalArgumentException" to the method signature. 3) 将“throws IllegalArgumentException”添加到方法签名中。 The java code-quality scanner I am using on my project claims that throwing a RuntimeException in the signature like this is a code smell and should be avoided.我在我的项目中使用的 java 代码质量扫描器声称,像这样在签名中抛出 RuntimeException 是一种代码味道,应该避免。

I was hoping someone could shed some light on if there is a good pattern for what I am looking to do.如果我想要做的事情有一个好的模式,我希望有人能阐明一些想法。 I can't tell if I am over-engineering things or thinking about this situation correctly.我不知道我是过度设计还是正确地考虑了这种情况。

I'd make your own checked exception - something like "NegativeNumberException", since that describes what caused this error.我会制作您自己的检查异常 - 类似于“NegativeNumberException”,因为它描述了导致此错误的原因。

RuntimeError s like IllegalArgumentException are generally intended to be thrown in case of programmer error - if you're expecting it to be caught, then you should use a checked one.IllegalArgumentException这样的RuntimeError通常是为了在程序员出错的情况下抛出——如果你希望它被捕获,那么你应该使用一个经过检查的。

You can always add a Javadoc connect with an @throws annotation, but it's better, from what you're describing, to have the compiler barf when a caller fails to handle the exception.您始终可以添加带有@throws注释的 Javadoc 连接,但根据您的描述,当调用者无法处理异常时让编译器 barf 更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM