I read this answer about when to use assertions, which basically says use it to have a test that's turned off in production: Appropriate use of assert
(The Oracle docs say As an added benefit, assertions serve to document the inner workings of your program, enhancing maintainability.
This makes sense, but I'm unclear why it's the added benefit as opposed to the only benefit.)
My thoughts are:
- If you want to check during development that something can "never happen" but turn off that check in production, it seems like it can be covered as part of unit tests that test for the edge case.
- I can see some benefit of having an assertion on a development environment that undergoes a lot of manual testing, so you get the benefit that with some probability an edge case comes up and the assertion catches it. However, since relying on this instead of a unit test implies you can't guarantee testing that edge case, you also can't guarantee it would "never happen" in production. Therefore, I would prefer using try/if in case it does come up during production.
- So that leaves what appears to be a pretty narrow set of use cases - assert when you can't write an effective test, but are pretty confident it won't come up in production, and you're very concerned about performance for this part of your code.
What am I misunderstanding? Thank you in advance for your help :)