Assertion (computing)

Assertion (computing)

In computer programming, an assertion is a predicate (i.e., a true–false statement) placed in a program to indicate that the developer "thinks" that the predicate is always true at that place.

For example, the following code contains two assertions:

x := 5;{x > 0}x := x + 1{x > 1}

x > 0 and x > 1, and they are indeed true at the indicated points during execution.

Assertions are used to help specify programs and to reason about program correctness. For example, a precondition — an assertion placed at the beginning of a section of code — determines the set of states under which the code is expected to be executed. A postcondition — placed at the end — describes the expected state at the end of execution.

The example above uses the notation for including assertions used by C.A.R. Hoare in his 1969 paper [C.A.R. Hoare, [http://lambda-the-ultimate.org/node/1912 "An axiomatic basis for computer programming"] , Communications of the ACM, 1969] . That notation cannot be used in existing main-stream programming languages, programmers include unchecked assertions using the comment feature of their programming language. Here is an example using C:

x = 5;// {x > 0}x = x + 1;// {x > 1}

The braces are included in the comment in order to help distinguish this use of a comment from other uses.

Several modern programming languages include checked assertions - statements that is checked at runtime or sometimes statically. If an assertion evaluates to false at run-time, an "assertion failure" results, which typically causes execution to abort. This draws attention to the location at which the logical inconsistency is detected and can be preferable to the behaviour that would otherwise result.

The use of assertions helps the programmer design, develop, and reason about a program.

Usage

In languages such as Eiffel, assertions are part of the design process, in others, such as C and Java, they are used only to check assumptions at 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 be a form of documentation: they can describe the state the code expects to find before it runs (its preconditions), and the state the code expects to result in when it is finished running (postconditions); they can also specify invariants of a class. In Eiffel, such assertions are integrated into the language and are automatically extracted 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 comments is that assertions can be checked every time the program is run; if the assertion no longer holds, an error can be reported. This prevents the code from getting out of sync with the assertions (a problem that can occur with comments).

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 code: int total = countNumberOfUsers(); if (total % 2 = 0) { // total is even } else { // total is odd assert(total % 2 = 1); }In Java, % is the "remainder" operator (not modulus) — if its first operand is negative, the result can also be negative. Here, the programmer has assumed that total 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 countNumberOfUsers does return a negative value, it is likely a bug in the program.

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-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 default clause of the switch statement in languages such as C, C++, and Java. Cases that are intentionally not handled by the programmer will raise an error and abort the program rather than silently continuing in an erroneous state.

In Java, assertions have been a part of the language since version 1.4. Assertion failures result in raising an AssertionError when the program is run with the appropriate flags, without which the assert statements are ignored. In C, they are added on by the standard header assert.h defining assert ("assertion") as a macro that signals an error in the case of failure, usually terminating the program. In standard C++ the header cassert is required instead. However, some C++ libraries still have the assert.h available.

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 context of the failed assertion if a user breakpoint is triggered instead of halting the program), the programmer can usually fix the problem. Thus, assertions are a very powerful tool in debugging.

Static assertions

Assertions that are checked at compile time are called static assertions. They should always be well-commented.

Static assertions are particularly useful in compile time template metaprogramming.

Disabling assertions

Most languages allow assertions to be enabled or disabled globally, and sometimes independently. Assertions are often enabled during development and disabled during final testing and on release to the customer. Not checking assertions avoiding the cost of evaluating the assertions while, assuming the assertions are free of side effects, still producing the same result under normal conditions. Under abnormal conditions, disabling assertion checking can mean that a program that would have aborted will continue to run. This is sometimes preferable.

Some languages, including C/C++, completely remove assertions at compile time using the preprocessor. Java require an option to be passed to the run-time engine in order to enable assertions. Absent the option, assertions are bypassed but they always remain in the code.

Programmers can always build checks into their code that are always active by bypassing or manipulating the languages normal assertion checking mechanisms.

Comparison with error handling

It is worth distinguishing assertions from routine error handling. Assertions should be used to document logically impossible situations and discover programming errors— if the "impossible" occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is unwise: assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Assertions also do not display a user-friendly error message.

Consider the following example of using an assertion to handle an error: int *ptr = malloc(sizeof(int) * 10); assert(ptr != NULL); // use ptr ...

Here, the programmer is aware that malloc will return a NULL pointer if memory is not allocated. This is possible: the operating system does not guarantee that every call to malloc will succeed. If an out of memory error occurs the program will immediately abort. Without the assertion, the program would continue running until ptr was dereferenced, and possibly longer, depending on the specific hardware being used. So long as assertions are not disabled, an immediate exit is assured. But if a graceful failure is desired, the program has to handle the failure. For example, a server may have multiple clients, or may hold resources that will not be released cleanly, or it may have uncommited changes to write to a datastore. In such cases it is better to fail a single transaction than to abort abruptly.

ee also

*Assertion definition language
*Design by contract
*Exception handling
*Hoare logic
*Static code analysis
*Java Modeling Language

References

External links

*" [http://research.microsoft.com/~thoare/6Jun_assertions_personal_perspective.htm Assertions: a personal perspective] " by Tony Hoare, 2001.
*" [http://www.stanford.edu/~pgbovine/programming-with-asserts.htm The benefits of programming with assertions] " by Philip Guo (Stanford University), 2008.
*Java:
** [http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html Programming With Assertions in Java]
**Technical Article " [http://java.sun.com/developer/JDCTechTips/2002/tt0409.html Using Assertions] "
* [http://www.assert-project.net The assert-project]


Wikimedia Foundation. 2010.

Игры ⚽ Нужно сделать НИР?

Look at other dictionaries:

  • Assertion — The term assertion has several meanings: * Assertion (computing), a computing programming technique * Logical assertion, logical assertion of a statement * Patent assertion, the enforcement of patent rights, usually by litigation against an… …   Wikipedia

  • Computing Machinery and Intelligence — Computing Machinery and Intelligence, written by Alan Turing and published in 1950 in Mind, is a seminal paper on the topic of artificial intelligence in which the concept of what is now known as the Turing test was introduced to a wide audience …   Wikipedia

  • Guard (computing) — In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question. The term is used at least in Haskell, Clean, Erlang, and OCaml programming languages. In… …   Wikipedia

  • Methods of computing square roots — There are several methods for calculating the principal square root of a nonnegative real number. For the square roots of a negative or complex number, see below. Contents 1 Rough estimation 2 Babylonian method 2.1 Example …   Wikipedia

  • Category:Logic in computer science — Logic in computer science is that branch of mathematical logic which is approximately the intersection between mathematical logic and computer science. It contains: Those investigations into logic that are guided by applications in computer… …   Wikipedia

  • C11 — или ISO/IEC 9899:2011 (неофициально C1X)  новый стандарт для языка Си (ISO/IEC 9899:2011[1]), который заменил существующий стандарт C99. Официально о выпуске стандарта было объявлено 19 декабря 2011 года[2]. Эта версия стандарта большей… …   Википедия

  • Debugging — Debug redirects here. For the shell command, see debug (command). For the German magazine, see Debug (magazine). A photo of the apocryphally first real bug, which was debugged in 1947. Debugging is a methodical process of finding and reducing the …   Wikipedia

  • QBA — Quantitative Business Analysis (Business » General) Quantitative Business Analysis (Governmental » Military) Quantitative Business Analysis (Academic & Science » Universities) Quantitative Business Analysis (Governmental » US Government) *… …   Abbreviations dictionary

  • Syādvāda — Part of a series on Jain philosophy Concepts Anekāntavāda · Syādvāda · Nayavāda · Jain Co …   Wikipedia

  • Turing's proof — First published in January 1937 with the title On Computable Numbers, With an Application to the Entscheidungsproblem , Turing s proof was the second proof of the assertion (Alonzo Church proof was first) that some questions are undecidable :… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”