0

Why using Introduce Assertion?

Syahriga Syahrul 5 years ago updated by Alexander Shvets 3 years ago 3

Hi there, i think it's clear in subject, since the assertion are using for test development, and not in production state. why using it just to remove comment? what is your consideration on using it?

+1

Hi Syahriga!

Thanks for asking. Let me answer your questions by simply quoting parts of the article for starters:

> Why using it just to remove comment?

Make these assumptions obvious by adding corresponding assertions. As with type hinting in method parameters, these assertions can act as live documentation for your code.

> What is your consideration on using it?

If the exception can be caused by actions of the user or system and you can handle the exception. On the other hand, ordinary unnamed and unhandled exceptions are basically equivalent to simple assertions – you don’t handle them and they’re caused exclusively as the result of a program bug that never should have occurred.

If you have a followup question, shoot it! I'd be happy to help.

Hi Alexander,

Sorry for necroing this old thread but I just wanted to expand on your answer. From your experience, do you think somebody might mind using Assert outside unit testing? Handling exceptions is better than returning nondescript nulls, however I just want to make sure when I get new job, somebody won't scoff at me for using Assert in such way.

Hi Tomasz!

To be 100% honest with you, the reaction of your team lead to your asserts in the production code will solely depend on his/her expertise and the project's code style conventions. Asserts in code are indeed not very common. I've seen assertions in non-unit-test code quite a few times in various projects over the years.

Usually, they are placed in such a way, that triggering them would mean that something that's very wrong happened to the project. Sure, you can replace them with exceptions, but that'll be just a waste of code for something that does the same thing. Personally, I'd use them if a simple assertion in code would spare me a very sophisticated unit-test that involves heavy mocking. Depending on the language you're working with, it's also possible to turn off assertions when building project for production.