一个好的 Java 合同设计库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1075719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:04:51  来源:igfitidea点击:

A good Design-by-Contract library for Java?

javadesign-by-contract

提问by Chris Jones

A few years ago, I did a survey of DbC packages for Java, and I wasn't wholly satisfied with any of them. Unfortunately I didn't keep good notes on my findings, and I assume things have changed. Would anybody care to compare and contrast different DbC packages for Java?

几年前,我对 Java 的 DbC 包进行了调查,我对其中任何一个都不完全满意。不幸的是,我没有很好地记录我的发现,我认为事情已经发生了变化。有人愿意比较和对比 Java 的不同 DbC 包吗?

采纳答案by Verhagen

There is a nice overview on WikiPedia about Design by Contract, at the end there is a section regarding languages with third party support libraries, which includes a nice serie of Java libraries. Most of these Java libraries are based on Java Assertions.

WikiPedia上有一个关于合同设计的很好的概述 ,最后有一个关于具有第三方支持库的语言的部分,其中包括一系列不错的 Java 库。这些 Java 库中的大多数都基于 Java 断言。

In the case you only need Precondition Checkingthere is also a lightweight Validate Method Argumentssolution, at SourceForge under Java Argument Validation(Plain Java implementation).

在您只需要前提条件检查的情况下,还有一个轻量级的Validate Method Arguments解决方案,在 SourceForge 下的Java Argument Validation(Plain Java implementation)。

Depending on your problem, maybe the OValframework, for field/property Constraints validation is a good choice. This framework lets you place the Constraints in all kind of different forms (Annotations, POJO, XML). Create customer constraints through POJO or scripting languages (JavaScript, Groovy, BeanShell, OGNL, MVEL). And it also party implements Programming by Contract.

根据您的问题,对于字段/属性约束验证,OVal框架可能是一个不错的选择。该框架允许您以各种不同的形式(注释、POJO、XML)放置约束。通过 POJO 或脚本语言(JavaScript、Groovy、BeanShell、OGNL、MVEL)创建客户约束。并且它也是一方实现了按合同编程

回答by user

Google has a open source library called contracts for java.

Google 有一个名为contract for java 的开源库。

Contracts for Java is our new open source tool. Preconditions, postconditions, and invariants are added as Java boolean expressions inside annotations. By default these do nothing, but enabled via a JVM argument, they're checked at runtime.

? @Requires, @Ensures, @ThrowEnsures and @Invariant specify contracts as Java boolean expressions
? Contracts are inherited from both interfaces and classes and can be selectively enabled at runtime

Contracts for Java 是我们新的开源工具。前置条件、后置条件和不变量作为 Java 布尔表达式添加到注释中。默认情况下,这些什么都不做,但通过 JVM 参数启用,它们在运行时被检查。

? @Requires, @Ensures, @ThrowEnsures and @Invariant specify contracts as Java boolean expressions
? Contracts are inherited from both interfaces and classes and can be selectively enabled at runtime

contracts for java.

java 的合约

回答by Janusz

I tested contract4J one time and found it usable but not perfect. You are creating contracts for for and after method calls and invars over the whole class.

我测试了一次 contract4J,发现它可用但并不完美。您正在为整个类的方法调用和 invars 和之后创建契约。

The contract is created as an assertion for the method. The Problem is that the contract itself is written in a string so you don't have IDE support for the contracts or compile time cheching if the contract still works.

合约被创建为方法的断言。问题是合同本身是用字符串编写的,因此如果合同仍然有效,您就没有合同的 IDE 支持或编译时检查。

A link to the library

图书馆的链接

回答by mattwright

It's been a long time since I've looked at these, but found some old links. One was for JASS.

我已经很久没有看过这些了,但找到了一些旧链接。一个是给JASS 的

The other one that I had used (and liked) was iContract by Reliable Systems. It had an ant task that you would run as a preprocessor. However, I can't seem to find it with some google searches, it looks like it has vanished. The original site is now a link farm. Check out this linkfor some possible ways to get to it.

我使用过(并喜欢)的另一个是 Reliable Systems 的 iContract。它有一个 ant 任务,您可以将其作为预处理器运行。但是,我似乎无法通过一些谷歌搜索找到它,它看起来已经消失了。原来的站点现在是一个链接农场。查看此链接以了解获取它的一些可能方法。

回答by Andre Steingress

There is a Groovy extensions that enables Design by Contract(tm) in Groovy/Java code - GContracts. It uses so-called closure annotations to specify class invariants, pre- and postconditions. Examples can be found on the project's github wiki.

有一个 Groovy 扩展可以在 Groovy/Java 代码中启用 Design by Contract(tm) - GContracts。它使用所谓的闭包注释来指定类不变量、前置条件和后置条件。可以在项目的 github wiki 上找到示例。

Major advantage: it is only a single jar without external dependencies and it can be resolved via Maven compliant repositories since its been placed in the central Maven repo.

主要优点:它只是一个没有外部依赖关系的 jar,并且可以通过 Maven 兼容的存储库解析,因为它被放置在中央 Maven repo 中

回答by keyoxy

If you want a plain and simple basic support for expressing your contracts, have a look on valid4j (found on Maven Central as org.valid4j:valid4j). It lets you express your contracts using regular hamcrest-matchers in plain code (no annotations, nor comments).

如果您想要一个简单明了的基本支持来表达您的合同,请查看 valid4j(在 Maven Central 中作为 org.valid4j:valid4j 找到)。它允许您使用普通的 hamcrest-matchers 以普通代码(无注释或注释)来表达您的合同。

For preconditions and postconditions (basically assertions -> throwing AssertionError):

对于前置条件和后置条件(基本上是断言 -> 抛出 AssertionError):

import static org.valid4j.Assertive.*;

require(inputList, hasSize(greaterThan(0)));
...
ensure(result, lessThan(4.0));

If you are not happy with the default global policy (throwing AssertionError), valid4j provides a customization mechanism that let's you provide your own implementation of org.valid4j.AssertiveProvider.

如果您对默认的全局策略(抛出 AssertionError)不满意,valid4j 提供了一种自定义机制,让您可以提供自己的 org.valid4j.AssertiveProvider 实现。

Links:

链接:

回答by iirekm

I would suggest a combination of a few tools:

我建议结合使用一些工具:

  • Java's assert condition...or it's more advanced Groovy cousin, Guava's Preconditions.checkXXXX(condition...)and Verify.verify(condition...), or a library like AssertJ, if all you need is just to do simple checks in your 'main' or 'test' code

  • you'll get more features with a tool like OVal; it can check both objects as well as method arguments and results, you can also fire checks manually (eg to show validation errors on UI before a method is called). It can understand existing annotations eg from JPA or javax.validation(like @NotNull, @Pattern, @Column), or you can write inline constraints like @Pre(expr="x >= 0 && x <= y"). If the annotation is @Documented, the checks will be also visible in Javadocs (you don't have to describe them there as well).

  • OVal uses reflection, which can make performance issues and other problems in some environments like Android; then you should consider tool like Google's Cofoja, which has less functionality, but depends on compile-time Annotation Processing Tool instead of reflection

  • Javaassert condition...或者更高级的 Groovy 表亲,GuavaPreconditions.checkXXXX(condition...)Verify.verify(condition...),或者像AssertJ这样的库,如果你需要的只是在你的“主”或“测试”代码中做简单的检查

  • 使用OVal 之类的工具,您将获得更多功能;它可以检查对象以及方法参数和结果,您还可以手动触发检查(例如,在调用方法之前在 UI 上显示验证错误)。它可以理解现有的注释,例如来自 JPA 或javax.validation(如@NotNull, @Pattern, @Column),或者您可以编写内联约束,如@Pre(expr="x >= 0 && x <= y"). 如果注释是@Documented,则检查也将在 Javadocs 中可见(您也不必在那里描述它们)。

  • OVal使用反射,在Android等一些环境下会出现性能问题等问题;那么你应该考虑像谷歌的 Cofoja这样的工具,它的功能较少,但依赖于编译时注释处理工具而不是反射

回答by reprogrammer

I'd highly recommend you to consider the Java Modeling Language (JML).

我强烈建议您考虑 Java 建模语言 ( JML)。

回答by Sudarshan

I personally think that the DbC libraries available at present have left a lot to be desired, none of the libraries i looked at played well with the Bean Validation API.

我个人认为目前可用的 DbC 库还有很多不足之处,我看过的库中没有一个与 Bean Validation API 配合得很好。

The libraries i looked at have been documented here

我查看的库已记录在此处

The Bean Validation API has a lot of over lap with the concepts from DbC. In certain cases Bean Validation API cannot be used like simple POJO's (non CDI managed code). IMO a think wrapper around the Bean Validation API should suffice.

Bean Validation API 与来自 DbC 的概念有很多重叠之处。在某些情况下,不能像简单的 POJO(非 CDI 托管代码)那样使用 Bean 验证 API。IMO 认为 Bean Validation API 的包装器就足够了。

I found that the existing libraries are a little tricky to add into existing web projects given that they are implemented either via AOP or Byte code instrumentation. Probably with the advent of Bean Validation API this kind of complexity to implement DbC is unwarranted.

我发现将现有库添加到现有 Web 项目中有点棘手,因为它们是通过 AOP 或字节代码检测实现的。可能随着 Bean Validation API 的出现,实现 DbC 的这种复杂性是没有根据的。

I have also documented my rant in this postand hope to build a small library which leverages on the Bean Validation API

我还在这篇文章中记录了我的咆哮,并希望构建一个利用 Bean Validation API 的小型库

回答by dfa

I think that many DbC libraries were surclassed by the builtin assertkeyword, introduced since Java 1.4:

我认为许多 DbC 库都由自 Java 1.4 以来引入的内置assert关键字分类:

  • it is a built-in, no other library is required
  • it works with inheritance
  • you can activate/deactivate on package basis
  • easy to refactoring (e.g. no assertions in comments)
  • 它是内置的,不需要其他库
  • 它适用于继承
  • 您可以在套餐基础上激活/停用
  • 易于重构(例如,注释中没有断言)