When designing your API/SDK functions in Kotlin, there are some useful functions that called Preconditions. Those functions can help you to ensure your functions are used in proper way. You can always define what are the requirements of your function in documentation. But Preconditions can prevent false use of the functions even if developer doesn’t care about reading the documentation.
I will show two of them in an example.
Let’s say we are writing a function to read characters in a file. This functions takes an argument as
filePath: String and returns the character count as
We designed our function only to read
.txt files. But developer can pass a path String to an
.xls file. We can prevent this by
require() function check. Basically
require() will check the String whether it contains
.txt. (Just take it as a dumb example)
And if it is something else, it will throw an IllegalArgumentException. So developer can know that it’s only possible to pass txt files.
Another function to use is
check() . Let’s continue with the same dumb example.
What if developer passed the txt file but it’s an empty one? With
check() we can check the state of the function whether the result have character sum. And if it’s zero, it will throw and IllegalStateException with a message.
checkare very similar in terms of behavior. But the main use case distinctions are:
require: way to specify expectations on arguments
check: way to specify expectations on the state
I’m sure there can be many other scenarios to use Preconditions rather than my dummy sample. We can make code self checking. And even the need for Unit Tests can be reduced.
Other options are:
You can check the source code here https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/kotlin/util/Preconditions.kt
Originally posted on https://medium.com/@uludagcan/kotlin-preconditions-in-api-design-548e44a2579a
Thanks for reading ❤️