Friday, February 13, 2004

Re: Assertions!!

i felt that your class invariant code was very dependant on assertions. if assertions were disabled then all the checking for data state consistency would be lost. is that not required during the normal working of the code and not only during debugging?

Right, assertions will be disabled when NOT debugging. When I say debugging... I really mean development, i.e. before release. You will generally have two builds of your code - Debug and Release. The Debug build has all the assertions enabled. In Release, it will be disabled. Assertions are expensive (depending on how much you use them)... so you will want to disable them before releasing for performance reasons as well.

As I said last time... assertions are for YOU. They are there to protect you from yourself. You are writing code in one method that somehow changes the class data, for example age, to 70, when the limit is 65. If you didn't have the assertions there, you wouldn't notice it. With the class invariant called in each method, the assertion will fail and you will see it.

Class invariants are akin to Unit Tests in a way... but integrated with the class. As you keep adding new code, you want to make sure that everything you wrote before works. You want to be sure that your new code didn't break anything before. Whereas Unit Tests test from the "outside" - as a consumer to the object, class invariants test from the "inside" to make sure the data is always in a valid state.

What happens when an assertion occurs? You get some error message telling you what line the assertion failed on and some other data. You should be the only one seeing that. Not the user. The user should see a friendly message.

What are your thoughts on assertions vs exceptions? When/Where dyou feel they should be used?

No comments: