Assertion (software development): Difference between revisions

Content deleted Content added
m linking
Assertions for run-time checking: not "side effect" in a technical sense
Line 70:
In [[Java (programming language)|Java]], <code>%</code> is the ''[[remainder]]'' operator (''[[Modulo operation|modulo]]''), and in Java, if its first operand is negative, the result can also be negative (unlike the modulo used in mathematics). Here, the programmer has assumed that <code>total</code> is non-negative, so that the remainder of a division with 2 will always be 0 or 1. The assertion makes this assumption explicit: if <code>countNumberOfUsers</code> does return a negative value, the program may have a bug.
 
A major advantage of this technique is that when an error does occur it is detected immediately and directly, rather than later through its often obscure [[Side effect (computer science)|side-effects]]. Since an assertion failure usually reports the code ___location, one can often pin-point the error without further debugging.
 
Assertions are also sometimes placed at points the execution is not supposed to reach. For example, assertions could be placed at the <code>default</code> clause of the <code>switch</code> statement in languages such as [[C (programming language)|C]], [[C++]], and [[Java (programming language)|Java]]. Any case which the programmer does not handle intentionally will raise an error and the program will abort rather than silently continuing in an erroneous state. In [[D (programming language)|D]] such an assertion is added automatically when a <code>switch</code> statement doesn't contain a <code>default</code> clause.