Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy way of null-checking constructor parameter

Tags:

groovy

I want to inject non-null values into my groovy class

class MyClass {
    private final String foo
    private final Integer bar

    MyClass(String foo, Integer bar) {
        // wanted ctr body
    }
    ...
}

Within the constructor, I want to assign the params to the respective fields AND prevent null values.

I wonder if there is a groovier way of doing this than the quite verbose

assert foo != null
assert bar != null
this.foo = foo
this.bar = bar

or

this.foo = Objects.requireNonNull foo
this.bar = Objects.requireNonNull bar
like image 751
Frank Neblung Avatar asked Dec 22 '22 19:12

Frank Neblung


2 Answers

If you use Groovy 3, you can use @NullCheck annotation that adds defensive conditions constructor (or any methods) arguments.

import groovy.transform.NullCheck

@NullCheck
class MyClass {
    private final String foo
    private final Integer bar

    MyClass(String foo, Integer bar) {
        this.foo = foo
        this.bar = bar
    }
}

// Examples:
new MyClass("test", null) // throws IllegalArgumentException("bar cannot be null")

new MyClass(null, "test") // throws IllegalArgumentException("foo cannot be null")

When you add @NullCheck on the class definition level, defensive null-check will be applied to all constructors and methods. Alternatively, you can add @NullCheck annotation to the methods (or constructors) you want to use this null-check only.

Before Groovy 3 such defensive checks have to be implemented manually.

like image 177
Szymon Stepniak Avatar answered Jan 08 '23 02:01

Szymon Stepniak


Only an important nuance, because the @NullCheck annotation only apply to explicit methods and constructos, as it is indicated in the official documentation.

http://docs.groovy-lang.org/next/html/gapi/groovy/transform/NullCheck.html

If placed at the class level, all explicit methods and constructors will be checked.

If you are using other annotations as @TupleConstructor, all the implicit methods and constructors are not going to check parameters are not null.

like image 33
Marcos Antonio Avatar answered Jan 08 '23 01:01

Marcos Antonio