Suggestion for a special "invalid" record?

P Holder pholder at gmail.com
Thu Oct 14 22:44:50 UTC 2021


I practically never write code that uses nulls.  I prefer instead to
make a specific instance of the class or interface that is known to be
UNSPECIFIED or INVALID (or whatever else reads well in the specific
case) and have it throw if someone tries to access it.  In cases where
a null would be returned as an error, I can then return this specific
case, or I can use it as an initializer for variables that will expect
a valid object eventually.    Here's an example of some [incomplete]
code I just wrote that did this:

interface EndpointID
{
  public static final EndpointID UNDEFINED = new EndpointID()
    {
      @Override
      public String getEndpointIDAsString()
      {
        throw getException("getEnpointIDAsString");
      }

      private RuntimeException getException(final String source)
      {
        return new IllegalStateException(String.format("Use of
%s.UNDEFINED by %s", EndpointID.class.getSimpleName(), source));
      }
    };

  String getEndpointIDAsString();
}

Now I came across a point in my code where it would have been more
handy (in some sense) to use a record instead of an interface as I did
above, and I wanted to do something similar.  I can't really think of
a way to do this easily because I can't inline instantiate the record
the same way I can a class (or can I somehow?)

This was the best I could come up with, and it's not very satisfying to me:

@org.eclipse.jdt.annotation.NonNullByDefault({})  // Need to disable
NULL processing for records
record LogMessageData(EndpointID endpointLogOriginatedFrom, Long
logMessageID, String SubsystemOfLog, String logMessage, String[]
parameters)
{
  public static final LogMessageData UNDEFINED_LOG_MESSAGE_DATA = new
LogMessageData(EndpointID.UNDEFINED, -1L, "UNDEFINED", "UNDEFINED",
new String[0]);

  int getNumberOfParameters() { return parameters.length; }
}

Can anyone suggest a better way, or can records be evolved to allow
for a better way?


More information about the amber-dev mailing list