2

I stumbled upon an article named Programming With Assertions.

And beside the mechanism of turning on and off assertions after compile time, I don't get it. Why were assertions introduced on language level, which is quite a big deal, isn't it?

I have never used assertions in production code, was never taught to use them in production code, and never saw assertions in production code. Beyond that, I would always prefer a more specific Exception over an AssertionError.

So here are my questions. Does anyone use assertions in production code, and what are the advantages of that usage?

gnat
  • 20,543
  • 29
  • 115
  • 306
Angelo.Hannes
  • 369
  • 2
  • 9

2 Answers2

1

Assertions are used to assert that a condition is always true. They're used in code to ensure that an assumption is correct.

Generally if you see an assertion error something bad has gone wrong.

You can read all about them at Wikipedia.

When it comes to using your own assertions, don't use them in place of exceptions. Instead, use them wherever you feel the need to assert that a condition always holds true, for example a value you may rely on in an internal data structure.

Sam
  • 6,172
0

Well technically speaking an assert normally gets compiled out of release builds so you wouldn't see them operate in code running in production. That said, you may still put them in to your application code as a kind of inline unit test so that they still do operate whilst your code is running in development/testing.

Normally unit tests run bits of application code and then check that certain things are true using asserts. That said there is still sometimes a reason to use an assert within the application code because, most importantly, a unit test can fail from an assert in the unit test code or an assert in the application code being tested.

Consider that you write a unit test that runs a contrived sequence of operations on your application that you suspect could theoretically cause bad things to happen. You might not have an easy way, from the scope unit test, to probe into your application classes to check if something is going wrong and there might be an easier alternative in adding the assert into the application code directly. Sometimes I write unit tests without an assert in the unit test itself, simply to attempt (and hopefully fail) to invoke one that I put in the application.

And a final note - asserts are not the same as exceptions. Exceptions are used for still expected (rare) behaviour and this can still be tested for as unit tests can be written to expect exceptions. Assertions are used for impossible unexpected behaviour and hence associated with the core concept of unit testing.

Benedict
  • 1,097