Skip to content

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?

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


You can write a single condition with Optional:

if (rule.getName() != null) {



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;
  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.