Guava 是否支持 Contract 类,或者以其他方式允许接口文档?
Does Guava support Contract Classes, or otherwise allow interface documentation?
我在看 Guava 的 Preconditions
。如果您在实现方法中使用它们,那就太好了,但是是否可以使用它们声明接口契约?
例如,在 C# Contracts 中你可以这样做 -
using System.Diagnostics.Contracts;
[ContractClass(typeof(FooContract))]
interface IFoo
{
void Bar(int i);
}
[ContractClassFor(typeof(IFoo))]
abstract class FooContract : IFoo
{
public void Bar(int i)
{
Contract.Requires(i >= 0);
}
}
在番石榴中有这样的可能吗?如果没有,是否还有另一个 java 库?
按合同设计是一种非常优雅的方法,但从未在 Java 中流行。早期的实现使用 XDoclet,然后是使用 AOP 代理的注释,以及后来的字节码预处理。一些实现的开销、它们的框架依赖性以及被定义为元数据使大多数开发人员无法在实践中采用该方法。有库,例如 Contracts For Java,但很少有人积极维护。
更常见的是显式验证检查,例如Java的Objects.requireNonNull
和Guava的Preconditions
。 JSR-303 Bean Validation is fairly common for data models but rarely used on interfaces. For interfaces its more popular to rely on unit tests and assistance by libraries, such as Guava's NullPointerTester
, to ensure that the contract is being honored. A style choice that many prefer is to use JSR-305 for improved documentation that static analyzers like Findbugs and ErrorProne can validate. JSR-308 类似,但尚未流行。
我在看 Guava 的 Preconditions
。如果您在实现方法中使用它们,那就太好了,但是是否可以使用它们声明接口契约?
例如,在 C# Contracts 中你可以这样做 -
using System.Diagnostics.Contracts;
[ContractClass(typeof(FooContract))]
interface IFoo
{
void Bar(int i);
}
[ContractClassFor(typeof(IFoo))]
abstract class FooContract : IFoo
{
public void Bar(int i)
{
Contract.Requires(i >= 0);
}
}
在番石榴中有这样的可能吗?如果没有,是否还有另一个 java 库?
按合同设计是一种非常优雅的方法,但从未在 Java 中流行。早期的实现使用 XDoclet,然后是使用 AOP 代理的注释,以及后来的字节码预处理。一些实现的开销、它们的框架依赖性以及被定义为元数据使大多数开发人员无法在实践中采用该方法。有库,例如 Contracts For Java,但很少有人积极维护。
更常见的是显式验证检查,例如Java的Objects.requireNonNull
和Guava的Preconditions
。 JSR-303 Bean Validation is fairly common for data models but rarely used on interfaces. For interfaces its more popular to rely on unit tests and assistance by libraries, such as Guava's NullPointerTester
, to ensure that the contract is being honored. A style choice that many prefer is to use JSR-305 for improved documentation that static analyzers like Findbugs and ErrorProne can validate. JSR-308 类似,但尚未流行。