Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Assertion (software development)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Usage == In languages such as [[Eiffel (programming language)|Eiffel]], assertions form part of the design process; other languages, such as [[C (programming language)|C]] and [[Java (programming language)|Java]], use them only to check assumptions at [[Runtime system|runtime]]. In both cases, they can be checked for validity at runtime but can usually also be suppressed. === Assertions in design by contract === Assertions can function as a form of documentation: they can describe the state the code expects to find before it runs (its [[precondition]]s), and the state the code expects to result in when it is finished running ([[postcondition]]s); they can also specify [[invariant (computer science)|invariants]] of a [[Class (computer science)|class]]. [[Eiffel (programming language)|Eiffel]] integrates such assertions into the language and automatically extracts them to document the class. This forms an important part of the method of [[design by contract]]. This approach is also useful in languages that do not explicitly support it: the advantage of using assertion statements rather than assertions in [[comment (computer programming)|comments]] is that the program can check the assertions every time it runs; if the assertion no longer holds, an error can be reported. This prevents the code from getting out of sync with the assertions. === Assertions for run-time checking === An assertion may be used to verify that an assumption made by the programmer during the implementation of the program remains valid when the program is executed. For example, consider the following [[Java (programming language)|Java]] code: <syntaxhighlight lang="java"> int total = countNumberOfUsers(); if (total % 2 == 0) { // total is even } else { // total is odd and non-negative assert total % 2 == 1; } </syntaxhighlight> 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 often obscure 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. In [[Java (programming language)|Java]], assertions have been a part of the language since version 1.4. Assertion failures result in raising an <code>AssertionError</code> when the program is run with the appropriate flags, without which the assert statements are ignored. In [[C (programming language)|C]], they are added on by the standard header <code>[[assert.h]]</code> defining <code> assert (''assertion'') </code> as a macro that signals an error in the case of failure, usually terminating the program. In [[C++]], both <code>assert.h</code> and <code>cassert</code> headers provide the <code>assert</code> macro. The danger of assertions is that they may cause side effects either by changing memory data or by changing thread timing. Assertions should be implemented carefully so they cause no side effects on program code. Assertion constructs in a language allow for easy [[test-driven development]] (TDD) without the use of a third-party library. === Assertions during the development cycle === During the [[development cycle]], the programmer will typically run the program with assertions enabled. When an assertion failure occurs, the programmer is immediately notified of the problem. Many assertion implementations will also halt the program's execution: this is useful, since if the program continued to run after an assertion violation occurred, it might corrupt its state and make the cause of the problem more difficult to locate. Using the information provided by the assertion failure (such as the location of the failure and perhaps a [[stack trace]], or even the full program state if the environment supports [[core dump]]s or if the program is running in a [[debugger]]), the programmer can usually fix the problem. Thus assertions provide a very powerful tool in debugging. === Assertions in production environment === When a program is deployed to [[production environment|production]], assertions are typically turned off, to avoid any overhead or side effects they may have. In some cases assertions are completely absent from deployed code, such as in C/C++ assertions via macros. In other cases, such as Java, assertions are present in the deployed code, and can be turned on in the field for debugging.<ref>[http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html Programming With Assertions], [http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html#enable-disable Enabling and Disabling Assertions]</ref> Assertions may also be used to promise the compiler that a given edge condition is not actually reachable, thereby permitting certain [[compiler optimizations|optimizations]] that would not otherwise be possible. In this case, disabling the assertions could actually reduce performance. === Static assertions === Assertions that are checked at compile time are called static assertions. Static assertions are particularly useful in compile time [[template metaprogramming]], but can also be used in low-level languages like C by introducing illegal code if (and only if) the assertion fails. [[C1X|C11]] and [[C++11]] support static assertions directly through <code>static_assert</code>. In earlier C versions, a static assertion can be implemented, for example, like this: <syntaxhighlight lang="c"> #define SASSERT(pred) switch(0){case 0:case pred:;} SASSERT( BOOLEAN CONDITION ); </syntaxhighlight> If the <code>(BOOLEAN CONDITION)</code> part evaluates to false then the above code will not compile because the compiler will not allow two [[Switch statement#C and languages with C-like syntax|case labels]] with the same constant. The boolean expression must be a compile-time constant value, for example <code>([[sizeof]](int)==4)</code> would be a valid expression in that context. This construct does not work at file scope (i.e. not inside a function), and so it must be wrapped inside a function. Another popular<ref>Jon Jagger, ''[http://www.jaggersoft.com/pubs/CVu11_3.html Compile Time Assertions in C]'', 1999.</ref> way of implementing assertions in C is: <syntaxhighlight lang="c"> static char const static_assertion[ (BOOLEAN CONDITION) ? 1 : -1 ] = {'!'}; </syntaxhighlight> If the <code>(BOOLEAN CONDITION)</code> part evaluates to false then the above code will not compile because arrays may not have a negative length. If in fact the compiler allows a negative length then the initialization byte (the <code>'!'</code> part) should cause even such over-lenient compilers to complain. The boolean expression must be a compile-time constant value, for example <code>(sizeof(int) == 4)</code> would be a valid expression in that context. Both of these methods require a method of constructing unique names. Modern compilers support a <code>__COUNTER__</code> preprocessor define that facilitates the construction of unique names, by returning monotonically increasing numbers for each compilation unit.<ref>[https://gcc.gnu.org/gcc-4.3/changes.html GNU, "GCC 4.3 Release Series β Changes, New Features, and Fixes"]</ref> [[D (programming language)|D]] provides static assertions through the use of <code>static assert</code>.<ref>{{cite web | url = http://dlang.org/version.html#StaticAssert | work = D Language Reference | title = Static Assertions | publisher = The D Language Foundation | accessdate = 2022-03-16}}</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)