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.
I use the java api for github to fetch repositories of a github organisation. Exceptions can occur in that code for 2 situations:
- fetching a GHOrganization instance (kotlin sample code)
- list repositories of a github organisation (java sample code)
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
Java code returns null
This code can be better!
Let’s not return nullables or null. Let’s return sealed classes:
Kotlin code returns sealed class
Java code returns sealed class
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:
Java Sealed Class
I create a Java sealed class that permits two final classes that hold the data (List< GHRepository> or String error): gfsdgsdfg
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 :
Kotlin Sealed Interface
Kotlin offers sealed interfaces as well. The code would be:
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
Java
Improved Code
Kotlin
Java
- code based on: Java 17 LTS and Kotlin 1.7
- screenshots: carbon.now.sh panda theme
- source code:
- gh.com/…/SealedClassesInterfaces (6 branches)
- cbrg.org/ls/SealedClassesInterfaces (6 branches)
Originally published at https://www.lotharschulz.info.