Frank Neblung
Frank Neblung

Reputation: 3175

Groovy way of null-checking constructor parameter

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

Upvotes: 4

Views: 2003

Answers (2)

Marcos Antonio
Marcos Antonio

Reputation: 93

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.

Upvotes: 1

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

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.

Upvotes: 9

Related Questions