r/Kotlin • u/ablativeyoyo • 2h ago
Null safety makes me write better code
I'm working on a security tool that has both GUI and networking code. There's configuration in the GUI and the configuration data is used in quite complex code that parses and modifies network traffic. Because the user is configuring the setup bit by bit in the GUI, various fields can be null. But the network section only works when the GUI is mostly configured.
If I'd written this in Java, realistically what I'd have done is chuck it together, fix a few glaring NPEs in early testing, and probably live with a few NPEs when it was partially configured. I realise this is not the textbook way of coding in Java, but realistically, that's what I would have done.
Kotlin of course doesn't let me do that. At first I used a few ?. and ?: calls to introduce null safety, but these were starting to look messy, and complicate the flow of code that is already quite complex. It made me realise that there's two conceptually different things here. There's a GUI model with nullable fields, and there's a config model with non-nullable fields. When the GUI is sufficiently completed, it can create a config model. This means the network code can skip the null checks, as the network code is only active if there is a config model.
Sure, I could have introduced this structure in Java, but would I have done that? This is especially relevant for people like me where my primary job is security and I am coding to help me do security work better, not as an end in itself.
