You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2020/04/04 11:54:38 UTC
[groovy] 02/02: GROOVY-9495: groovy.transform.NullCheck not
mentioned in release notes or language documentation
This is an automated email from the ASF dual-hosted git repository.
paulk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit d93d19fdb39b881fe6a3b06f6bdbb8fd05725d8b
Author: Paul King <pa...@asert.com.au>
AuthorDate: Sat Apr 4 21:54:28 2020 +1000
GROOVY-9495: groovy.transform.NullCheck not mentioned in release notes or language documentation
---
src/spec/doc/core-metaprogramming.adoc | 14 ++++++++++++++
src/spec/test/CodeGenerationASTTransformsTest.groovy | 20 ++++++++++++++++++++
2 files changed, 34 insertions(+)
diff --git a/src/spec/doc/core-metaprogramming.adoc b/src/spec/doc/core-metaprogramming.adoc
index e5e614b..5d34f41 100644
--- a/src/spec/doc/core-metaprogramming.adoc
+++ b/src/spec/doc/core-metaprogramming.adoc
@@ -1729,6 +1729,20 @@ It is also worthwhile examining the equivalent generated code where the `next` m
include::{projectdir}/src/spec/test/CodeGenerationASTTransformsTest.groovy[tags=autoimplement_code_equiv,indent=0]
----
+[[xform-NullCheck]]
+===== `@groovy.transform.NullCheck`
+
+The `@NullCheck` AST transformation adds null-check guard statements to constructors and methods
+which cause those methods to fail early when supplied with null arguments.
+It can be seen as a form of defensive programming.
+The annotation can be added to individual methods or constructors, or to the class
+in which case it will apply to all methods/constructors.
+
+[source,groovy]
+----
+include::{projectdir}/src/spec/test/CodeGenerationASTTransformsTest.groovy[tags=nullcheck,indent=0]
+----
+
==== Class design annotations
This category of annotations are aimed at simplifying the implementation of well-known design patterns (delegation,
diff --git a/src/spec/test/CodeGenerationASTTransformsTest.groovy b/src/spec/test/CodeGenerationASTTransformsTest.groovy
index b19775d..0d13450 100644
--- a/src/spec/test/CodeGenerationASTTransformsTest.groovy
+++ b/src/spec/test/CodeGenerationASTTransformsTest.groovy
@@ -1678,4 +1678,24 @@ class EmptyIterator implements java.util.Iterator<String> {
*/
'''
}
+
+ void testNullCheck() {
+ assertScript '''
+ import groovy.transform.NullCheck
+ import static groovy.test.GroovyAssert.shouldFail
+
+// tag::nullcheck[]
+@NullCheck
+String longerOf(String first, String second) {
+ first.size() >= second.size() ? first : second
+}
+
+assert longerOf('cat', 'canary') == 'canary'
+def ex = shouldFail(IllegalArgumentException) {
+ longerOf('cat', null)
+}
+assert ex.message == 'second cannot be null'
+// end::nullcheck[]
+'''
+ }
}