I understand that assertions check things that should be true, but an if statement can check the same condition. When would I use an assertion instead of an ordinary check or an exception, and how is it different from a test?
Why use assertions if I can just check a condition and throw an exception?
Answers
The distinction is mostly about what a failure means. An assertion says, โIf this is false, my assumptions about the code are wrong.โ An ordinary check handles a situation the program needs to deal with, such as invalid input or a failed network request.
For example, after an operation that removes an item from a collection, you might assert that its size is not negative. That's an invariant, a property that should hold whenever the collection is in a valid state. If it fails, you want to investigate the implementation rather than ask the user to try a different value.
Mechanically, an assertion can look a lot like an if statement that raises an error. Its value is that it makes the programmer's assumption visible and can stop execution close to the bug, before the bad state causes a harder-to-trace failure elsewhere.
Reply to this answer
Watch out for release behavior. Some languages or build configurations can disable assertions, while others may leave them enabled. Check the rules for the language and project you're using.
That means you shouldn't rely on an assertion to validate untrusted input or perform work the program needs. Use a normal check and return an error or throw an exception when the caller needs to know that an operation failed. An assertion can supplement that, but it isn't a replacement for required validation.
r.284!buttoncrate:
Also avoid putting necessary side effects inside an assertion condition. If the assertion is disabled, that work might not happen.
Reply to this answer
Tests and assertions work together. An automated test sets up a scenario and checks the result. An assertion in application code checks an assumption at the point where that code runs, whether it's reached by a test or another execution.
A test can miss a particular path or combination of values. An assertion on that path can help reveal a broken assumption when the path does get exercised, though it doesn't guarantee the path will ever be tested.
Reply to this answer
Where do you put them? Start with assumptions that matter to a piece of logic: a collection is sorted before a routine that relies on sorted order, or a result is within the range the algorithm promises. Don't assert every line. Pick checks that would make a failure easier to understand.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Ravlen.2g:
So an invariant is a rule about valid program state, not necessarily a check for something the user entered?
Velnor+8t:
Right. You might validate user input first, then assert properties that your own code should preserve after accepting it.