Richard Bucker

Assertions in Java and Go

Posted at — Jun 22, 2012

First and foremost assertions do not exist in Go at all. The language designers had a very specific opinion about it. On the Java side assert was converted to a keyword. This too is interesting and yet maybe not so much.When servers/daemons are designed in the erlang way where failure is an option then things like assertions are ok. The application will crash, possibly generate a core file, definitely generate a log entry, and then restart. It could be the best of all worlds, especially when you have certain expectations.Here’s the thing. Unlike the Python and erlang idioms java is strongly typed so it almost makes sense to test input ranges etc and throw exceptions when things go bad. Assertions on the other hand do pretty much the same thing by setting the expectation during development and testing. The idea that the java language designers had was that assertions cost time and space; and if assertions can be removed from production then speed and size are recouped. However, during production you lose the validation that you had during testing and dev. And while TDD etc are supposed to perform exhaustive testing that’s just never the case. Code coverage or not.If you think I talked myself around in circles just now… I agree. My head is spinning as a result. So here is the bottom line. Forget the keyword. Use the IF statement and generate your own AssertionError. Sadly you won’t win any coding awards for beauty or brevity but you have a chance at consistency and accuracy.