Subtype polymorphism is great for adding more entity types. Pattern matching is a better choice for adding more functionality. In many use cases, it’s likelier that more functionality is requested than that more entity types are requested.
In this article, we implement a program based on a set of simple requirements. First, we implement it using subtype polymorphism, then using pattern matching. Given these implementations, we add two more requirements and compare the necessary changes to implement the new requirements.
When use the term pattern matching, I’m referring to a limited subset. …
null is bad for representing the absence of a value, use
Optionals instead. Use
Optional.flatMap to chain multiple operations that might not return a value.
Let’s quickly recap what
nullis and what problem it entails.
The language Java allows every non-primitive variable to take the value
null. If a variable holds the value
null, then all method calls to it will fail with a
NullPointerException at runtime. The compiler can only give limited hints if a method call on a variable is safe. Therefore, the programmer needs to make assumptions if a method call is safe. If he is wrong…
I’m a senior software engineer working in Bonn at LeanIX. I write about software development best practices across multiple programming languages.