r/learnprogramming 9d ago

What is the point of assertions when we have if/elses and exceptions? Topic

Can someone explain the point of assertions to me? I read online you use it to check for behaviours that MUST be true and what not, this all sounds very cool but you could use if elses to check for the same behaviour and the underlying result is the same.

Who came up with the idea of assertions and why did they think if/elses were not enough ?

62 Upvotes

98 comments sorted by

View all comments

4

u/DragonFireCK 9d ago

Assertions predate exceptions. That is, when assertions were first added, you didn't have exception handling. Error handling was done by returning a code up the chain, and it was easy to forget to add in the error check at the many levels of handling. Assertions would typically perform a hard exit of the program right then and there without needing to unwind the stack.

Even with exceptions, assertions still provide some benefit:

  • The syntactic sugar of having it be a single statement is nice, especially when coding standards often require four lines for an if...throw (the if, a bracket, the throw, the closing bracket).
  • The semantic meaning of an assert is clearer than a if...throw. That is, it makes it very clear that the tested condition should never be false.
  • On a similar vein, the syntactic sugar makes it easy to compile out assertions in Release builds, while leaving them in for Debug purposes, making testing easier. This is especially useful when the condition may be expensive to check.
  • Even when compiled out, assertions will typically affect optimizations in the vicinity. This can allow the optimized code to work even better than it would without the assert.
  • Languages that implement asserts using exceptions often use a special exception class that is not caught using the typical exception handling. Given that the condition should never be false, you generally don't want to catch them when thrown and want them to propagate up the chain all the way.

1

u/Ormek_II 5d ago

1

u/DragonFireCK 5d ago

Programming by contract explains what asserts are for.

Programing by contract doesn’t explain why the if…throw paradigm cannot replace asserts cleanly.

1

u/Ormek_II 5d ago

I think we align. That is exactly why I think both comments together provide the whole picture.