Skip to content
Advertisement

Java Code modularization, check if they are all null or not

Is there any clean way to check if they are all null or not for example getDescription(), getName(), getScript(), getTargets() and getTrigger() is null or not, checking in one line?

              ruleBean.setDescription(rule.getDescription());
          } else if (rule.getName() != null) {
              ruleBean.setName(rule.getName());
          } else if (rule.getScript() != null) {
              ruleBean.setScript(rule.getScript());
          } else if (rule.getTargets() != null) {
              ruleBean.setTargets(rule.getTargets());
          } else if (rule.getTrigger() != null) {
              ruleBean.setTrigger(rule.getTrigger());
          } else {
              return ResponseBean.builder().withData(request.getData())
                      .withMessage("No data provided for rule update").asFailure().build();
          } ```

Advertisement

Answer

You can write a single condition with Optional:

if (rule.getName() != null) {
 ruleBean.setName(rule.getName());
}

becomes:

Optional.ofNullable(rule.getName()).ifPresent(ruleBean::setName);

It’s harder to chain this to give the “if else” behaviour you have, though.

It looks like what you’re trying to detect with the “if/else” is whether some update was performed. To achieve this, you could have a method like:

<T> boolean did(T value, Consumer<? super T> consumer) {
  if (value == null) return false;
  consumer.accept(value);
  return true;
}

Then you can write your chain as:

boolean didSomething =
    did(rule.getName(), ruleBean::setName)
    || did(rule.getScript(), ruleBean::setScript) /* etc */;

if (!didSomething) {
  // Return your error response.
}

Because of the short-circuiting behaviour of ||, this will stop after the first call to did which “did” something, like the if/else if.

And if you actually want to apply the update for any non-null value, simply change || to |. The value of didSomething is still false if none of the conditions matched, as before.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement