5

Might there be a way in IntelliJ 2018 to auto-generate the lines of code checking for null values passed in any argument?

I want IntelliJ to change this:

// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity ) {
    this.localDate = localDate;
    this.name = name;
    this.quantity = quantity;
}

…to this:

// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity , BigDecimal quality , BigDecimal realmq , BigDecimal cost ) {
    Objects.requireNonNull( localDate );  // ⬅ Generate these checks for null values.
    Objects.requireNonNull( name );
    Objects.requireNonNull( quantity );

    this.localDate = localDate;
    this.name = name;
    this.quantity = quantity;
}

Even better would be if IntelliJ could write all the argument-to-member assignments and use the Objects.requireNonNull. So this:

// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity , BigDecimal quality , BigDecimal realmq , BigDecimal cost ) {
}

…would become this:

// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity ) {
    this.localDate = Objects.requireNonNull( localDate );  // ⬅ Generate all these lines entirely.
    this.name = Objects.requireNonNull( name );
    this.quantity = Objects.requireNonNull( quantity );
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • You can create a [Live Template](https://www.jetbrains.com/help/idea/creating-and-editing-live-templates.html) to do that. – Andreas Jan 05 '19 at 00:12
  • 3
    Do you have a good reason not to want to use the return value? `this.localDate = Objects.requireNonNull(localDate);`? – Andy Turner Jan 05 '19 at 00:21
  • @AndyTurner Oh, yes, even better. I never noticed that return value. Thanks! Editing the Question now to reflect that. – Basil Bourque Jan 05 '19 at 00:30

1 Answers1

6

You could try the following:

In Settings / Live template create a new live template

enter image description here

define the $content$ variable with [Edit Variables]:

enter image description here

with the following groovyScript:

groovyScript("def params = _1.collect { 'this.' + it + ' = Objects.requireNonNull(' + it + ');' }.join(); params", methodParameters());

now when you use the abbreviation

enter image description here

you should get the following

enter image description here

Let me know if it helps.

hce
  • 1,107
  • 9
  • 25