Replace null with amazing Kotlin and Java sealed classes & interfaces

Imagine a situation when you use in Kotlin or Java code a library that can throw exceptions. The calling function or method may return null if an exception is caught.

~ 5 minutes read
No time, jump straight to the conclusion

I use the java api for github to fetch repositories of a github organisation. Exceptions can occur in that code for 2 situations:

The calling function or method returns null if exceptions are caught.
The kotlin function returns a nullable type. However, the java method return value can be null.

Kotlin code returns nullables

source

Java code returns null

source

This code can be better!

Let’s not return nullables or null. Let’s return sealed classes:

Kotlin code returns sealed class

source

Java code returns sealed class

source

Whats inside sealed classes?

Kotlin Sealed Class

I use Kotlin data classes as container for the actual data (GHOrganization instance or error string) inside the sealed class:

source

Java Sealed Class

I create a Java sealed class that permits two final classes that hold the data (List<GHRepository> or String error):

source
source
source

Java Sealed Interface and Records

The two java final classes contain boilerplate code (getters and the constructors). Lets improve this part of the code with sealed interfaces and records :

source
source
source

Kotlin Sealed Interface

Kotlin offers sealed interfaces as well. The code would be:

source

However, the Kotlin code using sealed interfaces is not better compared to the code with sealed class usage only. Actually I am against using sealed interfaces in this particular use case.

Conclusion

Avoid returning nulls if exceptions are caught with wrapping success and error cases into sealed classes and interfaces.

Code smell

Kotlin

source

Java

source

Improved Code

Kotlin

source
source

Java

source
source
source
source

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.