Kotlin Preconditions in API Design

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.

Preconditions.kt file

I will show two of them in an example. require() and check()

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 Int.

OK, maybe not the best example but it tells the story 🙂

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.

Actually both require and check are 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:

requireNotNull() , checkNotNull and error()

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 ❤️


Ask me on TwitterInstagram or Linkedin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: