Leveraging Java Type System to Represent Special States

Sergiy Yevtushenko
4 min readSep 3, 2021

As every Java developer know, variables with non-primitive types are initialized to null. This is the Java (and not just Java) way to say that "value is missing" or "variable has no value assigned yet".

There are often situations when we may return value, but sometimes we need to notify the caller that there is an error. The idiomatic Java way to do this is to throw an exception.

What described above situations have in common? They cover different cases and use different ways to represent/handle them.

In fact, both of them deal with special states of the variables. There is also a third special case, as you’ll see below.

Variable Special States

What is the variable special state? The special state of the variable is the state, when the value of the variable is not (yet) available for some reason.

There are three special states of the variables:

  • Variable value is missing
  • Operation may return a value or report an error, so a value might be present or not
  • Variable holds a result of the asynchronous operation which is still in progress, so the value is not yet available.

Let’s take a look how these cases handled traditionally.

Missing Value

The traditional Java way to represent missing is to assign a null to the…

--

--