Search code examples
javaoption-typemethod-chainingnotnull

Java Method Chaining Optionally based on arguments


If a 3rd party requests an argument attachments in a method, how may I avoid using an if and break method chaining, knowing that my argument may be null? The method has the following definition.

// import org.jetbrains.annotations.NotNull;
EmailBuilder withAttachments(@NotNull List<Attachment> attachments);

I would prefer NOT using an if condition for .withAttachments, when attachments == null. I know that javascript has method?(), but what is appropriate for java8, or above? In the case where (attachments == null), I don't want to call .withAttachments() at all. But, I don't see syntax comparable to methodA?() like in javascript, or typescript.

return emailBuilder()
  .withSubject(email.getSubject())
  .withReplyTo(replyAddresses)
  .withAttachments(attachments) // This is conditional...based on attachments
  .withHeader("X-showheader", email.getShowHeader());
  .build();

Would I be required to do this?

EmailBuilder eb = emailBuilder()
  .withSubject(email.getSubject())
  .withReplyTo(replyAddresses);
  if(attachments)
    eb = eb.withAttachments(attachments); // This is conditional...based on attachments
  eb = eb.withHeader("X-showheader", email.getHeader())
  .build;
return eb;

Solution

  • I'm assuming you can't change the contract of withAttachments to ignore calls with null? You could, upstream wrap attachments in an Optional and then provide an orElse with an empty, but not null, impl of whatever type attachments is, e.g. (assuming attachments is a List):

    Optional<...> optionalAttachments = Optional.ofNullable(attachments);
    
    ...
    
    .withAttachments(optionalAttachments.orElse(Collections.emptyList())
    

    UPDATE (based on input from comment, hat tip to Andreas)

    You could also achieve this with a ternary, e.g.:

    .withAttachments(attachments != null ? attachments : Collections.emptyList())