How jspecify fits with builder pattern?

56 views
Skip to first unread message

a

unread,
Jun 19, 2025, 8:17:31 AMJun 19
to jspecify-discuss
Hello. I have immutable bean with lots of fields and builder for it:

@NullMarked
public class A {

  private final String hello;
  private final @Nullable Integer world;

  public static Builder newBuilder() {
    return new Builder();
  }

  public A(String hello, @Nullable Integer world) {
    this.hello = Objects.requireNonNull(hello);
    this.world = world;
  }

  public String getHello() {
    return hello;
  }

  public @Nullable Integer getWorld() {
    return world;
  }

  public static class Builder {

    private String hello;
    private @Nullable Integer world;

    public String getHello() {
      return hello;
    }

    public void setHello(String hello) {
      this.hello = hello;
    }

    public @Nullable Integer getWorld() {
      return world;
    }

    public void setWorld(@Nullable Integer world) {
      this.world = world;
    }

    public A build() {
      return new A(hello, world);
    }
  }
}

IDE claims about hello field in builder (and CI system stops the build):
Screenshot from 2025-06-19 14-21-53.png
I can't initialize this field, because there's no suitable default value according to business logic of my object (even empty string). I can't mark this field as nullable, because this defeats main purpose of jspecify - take guidance for developer which fields are optional and which not.

It's ok that hello field takes null. Later it will be set by developer.

How to deal with this situation?

Manu Sridharan

unread,
Jun 19, 2025, 8:39:04 AMJun 19
to a, jspecify-discuss
Hi, I think the typical solution here is to mark the `Builder.hello` field as @Nullable and then to do an `Objects.requireNonNull(hello)` call in `Builder.build` to ensure that it has been set.  The property you want to enforce here is that on any Builder object, the `setHello` method is called before the `build` method, which is outside the scope of most nullness checkers.  The Called Methods Checker from the Checker Framework (which I helped to develop) is able to check this type of method call ordering property at compile time, but that is outside of JSpecify.

Best,
Manu 

--
You received this message because you are subscribed to the Google Groups "jspecify-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jspecify-discu...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/jspecify-discuss/cb338fce-4afc-4928-bd9c-01a72a57f687n%40googlegroups.com.


Reply all
Reply to author
Forward
0 new messages