Как использовать assertions в Java
Используйте assertions (утверждения или ассерты) Java для проверки корректности кода и для ускорения тестирования и отладки ваших программ.
Написание программ, которые правильно работают, может оказаться сложной задачей. Поскольку наши предположения о том, как будет вести себя код при выполнении, часто ошибочны. Использование ассертов в Java — это один из способов проверить правильность логики программирования.
В этом руководстве рассказывается об ассертах в Java. Сначала вы узнаете, что такое ассерты и как их определять и использовать в коде. Далее вы узнаете, как использовать ассерты для обеспечения выполнения предварительных и постусловий. Наконец, вы сравните ассерты с исключениями и выясните, зачем в коде нужно и то и другое.
Загрузите исходный код примеров для этой статьи. Создано Джеффом Фризеном для JavaWorld.
Что такое ассерты в Java?
До JDK 1.4 разработчики часто использовали комментарии для документирования предположений о правильном использовании методов программы. Однако комментарии бесполезны как механизм для проверки и отладки предположений. Компилятор игнорирует комментарии, поэтому нет возможности использовать их для обнаружения ошибок. Разработчики также часто не обновляют комментарии при изменении кода.
В JDK 1.4 ассерты были введены как новый механизм для тестирования и отладки кода. По сути, ассерты — это компилируемые сущности, которые выполняются в runtime, если вы включили их для тестирования программы. Вы можете запрограммировать ассерты так, чтобы они уведомляли вас об ошибках ещё до того как они произошли и программа “упала”, что значительно сокращает время на отладку неисправной программы.
Ассерты используются для определения требований, исполнение которых делают программу правильной. И делается это при помощи проверки условий (логических выражений) на true. Если же выражение выдаёт false, разработчик получает уведомление об этом. Использование утверждений может значительно повысить вашу уверенность в правильности кода.
Как написать ассерт на Java
Ассерты реализуются с помощью оператора assert и класса java.lang.AssertionError. Этот оператор начинается с ключевого слова assert и продолжается логическим выражением. Синтаксически это выражается следующим образом:
Если значение BooleanExpr истинно, ничего не происходит и выполнение продолжается. Однако, если выражение оценивается как ложное, бросается AssertionError, как, например, в этом коде:
Листинг 1: AssertDemo.java (версия 1)
ассерт здесь говорит о том, что по мнению разработчика переменная x должна быть больше или равна 0. Однако это явно не так; выполнение оператора assert приводит к выбросу AssertionError.
Это сообщение несколько загадочно, так как не указывает, что привело к AssertionError. Если вам нужно более информативное сообщение, используйте assert с таким синтаксисом:
Здесь expr любое выражение, включая вызов метода (прим.пер.: в соответствии с лучшими современными практиками рекомендуется отказаться от вызовов методов из ассертов), которое должно возвращать значение — вы не можете вызвать метод void. Удобно использовать просто строку, описывающую причину сбоя, как показано ниже:
Листинг 2: AssertDemo.java (версия 2)
Запустите этот код с включенными ассертами. На этот раз вы увидите чуть больше информации, объясняющей причину выброса AssertionError:
Предварительные условия и постусловия
Ассерты проверяют предварительные и постусловия на true, и предупреждают разработчика, когда происходит нарушение:
Предварительные условия
Вы можете обеспечить выполнение предварительных условий для общедоступных конструкторов и методов, выполнив явные проверки и выбрасывая исключения при необходимости. Для private вспомогательных методов вы можете обеспечить выполнение предварительных условий, используя ассерты. Рассмотрим листинг 3.
Листинг 3: AssertDemo.java (версия 3)
Постусловия
Постусловия обычно указываются через ассерты, независимо от того, является ли метод (или конструктор) общедоступным. Рассмотрим такой код:
Листинг 4: AssertDemo.java (версия 4)
Этот пример демонстрирует важную характеристику ассертов — их выполнение, обычно, ресурсозатратно. По этой причине в промышленной версии программы ассерты обычно отключены. В методе isSorted() необходимо сканировать весь массив, что может занять много времени в случае большого массива.
Ассерты против исключений в Java
Разработчики используют ассерты для документирования логически запрещённых ситуаций и для обнаружения ошибок в логике программы. Во время её выполнения включенный ассерт предупреждает разработчика о логической ошибке. Разработчик меняет исходный код, чтобы исправить логическую ошибку, а затем перекомпилирует этот код.
Разработчики используют механизм исключений Java для ответа на нефатальные (например, нехватку памяти) ошибки, которые могут быть вызваны факторами окружающей среды, такими как несуществующий файл, или плохо написанным кодом, например попыткой разделить на 0. Обработчик исключений часто пишется так, чтобы после ошибки программа могла продолжить работу.
Ассерты не заменяют исключения. В отличие от исключений, ассерты не поддерживают восстановление после ошибок (ассерты обычно немедленно останавливают выполнение программы — AssertionError не предназначены для перехвата); они часто отключены в промышленном коде; и они обычно не отображают удобные для пользователя сообщения об ошибках (хотя это не проблема assert). Важно знать, когда использовать исключения, а не ассерты.
Когда использовать исключения
Предположим, вы написали sqrt()метод, который вычисляет квадратный корень из своего параметра. В контексте действительных чисел невозможно извлечь квадратный корень из отрицательного числа. Следовательно, вы используете ассерт для отказа от исполнения метода, если аргумент отрицательный. Рассмотрим следующий фрагмент кода:
Неуместно использовать ассерт для проверки аргумента в этом public методе. Ассерт предназначен для обнаружения ошибок в логике программирования, а не для защиты метода от ошибочных значений параметров. Кроме того, если ассерты отключены, невозможно решить проблему отрицательного аргумента. Лучше создать исключение следующим образом:
Разработчик может выбрать, обрабатывать исключение недопустимого аргумента или пробросить его, и тогда сообщение об ошибке отображается инструментом, запускающим программу. Прочитав сообщение об ошибке, разработчик может исправить код, вызвавший исключение.
В этом руководстве вы узнали, как использовать ассерты для документирования правильной логики программы. Вы также узнали, почему ассерты не заменяют исключения, и вы видели пример, в котором использование исключения было бы более эффективным.
Этот рассказ «Как использовать ассерты в Java» был первоначально опубликован JavaWorld .
Перевод Академии Progwards
Programming With Assertions
An assertion is a statement in the Java TM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.
Experience has shown that writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs. As an added benefit, assertions serve to document the inner workings of your program, enhancing maintainability.
This document shows you how to program with assertions. It covers the topics:
Introduction
The assertion statement has two forms. The first, simpler form is:
where Expression 1 is a boolean expression. When the system runs the assertion, it evaluates Expression 1 and if it is false throws an AssertionError with no detail message.
The second form of the assertion statement is:
The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.
In some cases Expression 1 may be expensive to evaluate. For example, suppose you write a method to find the minimum element in an unsorted list, and you add an assertion to verify that the selected element is indeed the minimum. The work done by the assert will be at least as expensive as the work done by the method itself. To ensure that assertions are not a performance liability in deployed applications, assertions can be enabled or disabled when the program is started, and are disabled by default. Disabling assertions eliminates their performance penalty entirely. Once disabled, they are essentially equivalent to empty statements in semantics and performance. See Enabling and Disabling Assertions for more information.
The addition of the assert keyword to the Java programming language has implications for existing code. See Compatibility With Existing Programs for more information.
Putting Assertions Into Your Code
There are many situations where it is good to use assertions, including:
There are also situations where you should not use them:
The program would work fine when asserts were enabled, but would fail when they were disabled, as it would no longer remove the null elements from the list. The correct idiom is to perform the action before the assertion and then assert that the action succeeded:
As a rule, the expressions contained in assertions should be free of side effects: evaluating the expression should not affect any state that is visible after the evaluation is complete. One exception to this rule is that assertions can modify state that is used only from within other assertions. An idiom that makes use of this exception is presented later in this document.
Internal Invariants
Before assertions were available, many programmers used comments to indicate their assumptions concerning a program’s behavior. For example, you might have written something like this to explain your assumption about an else clause in a multiway if-statement:
You should now use an assertion whenever you would have written a comment that asserts an invariant. For example, you should rewrite the previous if-statement like this:
Note, incidentally, that the assertion in the above example may fail if i is negative, as the % operator is not a true modulus operator, but computes the remainder, which may be negative.
Another good candidate for an assertion is a switch statement with no default case. The absence of a default case typically indicates that a programmer believes that one of the cases will always be executed. The assumption that a particular variable will have one of a small number of values is an invariant that should be checked with an assertion. For example, suppose the following switch statement appears in a program that handles playing cards:
It probably indicates an assumption that the suit variable will have one of only four values. To test this assumption, you should add the following default case:
If the suit variable takes on another value and assertions are enabled, the assert will fail and an AssertionError will be thrown.
An acceptable alternative is:
This alternative offers protection even if assertions are disabled, but the extra protection adds no cost: the throw statement won’t execute unless the program has failed. Moreover, the alternative is legal under some circumstances where the assert statement is not. If the enclosing method returns a value, each case in the switch statement contains a return statement, and no return statement follows the switch statement, then it would cause a syntax error to add a default case with an assertion. (The method would return without a value if no case matched and assertions were disabled.)
Control-Flow Invariants
The previous example not only tests an invariant, it also checks an assumption about the application’s flow of control. The author of the original switch statement probably assumed not only that the suit variable would always have one of four values, but also that one of the four cases would always be executed. It points out another general area where you should use assertions: place an assertion at any location you assume will not be reached. The assertions statement to use is:
For example, suppose you have a method that looks like this:
Replace the final comment so that the code now reads:
Preconditions, Postconditions, and Class Invariants
While the assert construct is not a full-blown design-by-contract facility, it can help support an informal design-by-contract style of programming. This section shows you how to use asserts for:
Preconditions
By convention, preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. For example:
You can, however, use an assertion to test a nonpublic method’s precondition that you believe will be true no matter what a client does with the class. For example, an assertion is appropriate in the following «helper method» that is invoked by the previous method:
Note, the above assertion will fail if MAX_REFRESH_RATE is greater than 1000 and the client selects a refresh rate greater than 1000. This would, in fact, indicate a bug in the library!
Lock-Status Preconditions
Classes designed for multithreaded use often have non-public methods with preconditions relating to whether or not some lock is held. For example, it is not uncommon to see something like this:
A static method called holdsLock has been added to the Thread class to test whether the current thread holds the lock on a specified object. This method can be used in combination with an assert statement to supplement a comment describing a lock-status precondition, as shown in the following example:
Note that it is also possible to write a lock-status assertion asserting that a given lock isn’t held.
Postconditions
You can test postcondition with assertions in both public and nonpublic methods. For example, the following public method uses an assert statement to check a post condition:
Occasionally it is necessary to save some data prior to performing a computation in order to check a postcondition. You can do this with two assert statements and a simple inner class that saves the state of one or more variables so they can be checked (or rechecked) after the computation. For example, suppose you have a piece of code that looks like this:
Here is how you could modify the above method to turn the textual assertion of a postcondition into a functional one:
You can easily generalize this idiom to save more than one data field, and to test arbitrarily complex assertions concerning pre-computation and post-computation values.
You might be tempted to replace the first assert statement (which is executed solely for its side-effect) by the following, more expressive statement:
Don’t make this replacement. The statement above would copy the array whether or not asserts were enabled, violating the principle that assertions should have no cost when disabled.
Class Invariants
A class invariant is a type of internal invariant that applies to every instance of a class at all times, except when an instance is in transition from one consistent state to another. A class invariant can specify the relationships among multiple attributes, and should be true before and after any method completes. For example, suppose you implement a balanced tree data structure of some sort. A class invariant might be that the tree is balanced and properly ordered.
The assertion mechanism does not enforce any particular style for checking invariants. It is sometimes convenient, though, to combine the expressions that check required constraints into a single internal method that can be called by assertions. Continuing the balanced tree example, it might be appropriate to implement a private method that checked that the tree was indeed balanced as per the dictates of the data structure:
Because this method checks a constraint that should be true before and after any method completes, each public method and constructor should contain the following line immediately prior to its return:
It is generally unnecessary to place similar checks at the head of each public method unless the data structure is implemented by native methods. In this case, it is possible that a memory corruption bug could corrupt a «native peer» data structure in between method invocations. A failure of the assertion at the head of such a method would indicate that such memory corruption had occurred. Similarly, it may be advisable to include class invariant checks at the heads of methods in classes whose state is modifiable by other classes. (Better yet, design classes so that their state is not directly visible to other classes!)
Advanced Uses
The following sections discuss topics that apply only to resource-constrained devices and to systems where asserts must not be disabled in the field. If you have no interest in these topics, skip to the next section, «Compiling Files that Use Assertions».
Removing all Trace of Assertions from Class Files
Programmers developing applications for resource-constrained devices may wish to strip assertions out of class files entirely. While this makes it impossible to enable assertions in the field, it also reduces class file size, possibly leading to improved class loading performance. In the absence of a high quality JIT, it could lead to decreased footprint and improved runtime performance.
The assertion facility offers no direct support for stripping assertions out of class files. The assert statement may, however, be used in conjunction with the «conditional compilation» idiom described in the Java Language Specification, enabling the compiler to eliminate all traces of these asserts from the class files that it generates:
Requiring that Assertions are Enabled
Programmers of certain critical systems might wish to ensure that assertions are not disabled in the field. The following static initialization idiom prevents a class from being initialized if its assertions have been disabled:
Put this static-initializer at the top of your class.
Compiling Files That Use Assertions
This flag is necessary so as not to cause source compatibility problems.
Enabling and Disabling Assertions
By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions.
If a single command line contains multiple instances of these switches, they are processed in order before loading any classes. For example, the following command runs the BatTutor program with assertions enabled in package com.wombat.fruitbat but disabled in class com.wombat.fruitbat.Brickbat :
The above switches apply to all class loaders. With one exception, they also apply to system classes (which do not have an explicit class loader). The exception concerns the switches with no arguments, which (as indicated above) do not apply to system classes.This behavior makes it easy to enable asserts in all classes except for system classes, which is commonly desirable.
For example, the following command runs the BatTutor program with assertions enabled in system classes, as well as in the com.wombat.fruitbat package and its subpackages:
The assertion status of a class (enabled or disabled) is set at the time it is initialized, and does not change. There is, however, one corner case that demands special treatment. It is possible, though generally not desirable, to execute methods or constructors prior to initialization. This can happen when a class hierarchy contains a circularity in its static initialization.
If an assert statement executes before its class is initialized, the execution must behave as if assertions were enabled in the class. This topic is discussed in detail in the assertions specification in the Java Language Specification.
Compatibility With Existing Programs
Design FAQ
Here is a collection of frequently asked questions concerning the design of the assertion facility.
General Questions
Although ad hoc implementations are possible, they are of necessity either ugly (requiring an if statement for each assertion) or inefficient (evaluating the condition even if assertions are disabled). Further, each ad hoc implementation has its own means of enabling and disabling assertions, which lessens the utility of these implementations, especially for debugging in the field. As a result of these shortcomings, assertions have never become a part of the culture among engineers using the Java programming language. Adding assertion support to the platform stands a good chance of rectifying this situation.
We recognize that a language change is a serious effort, not to be undertaken lightly. The library approach was considered. It was, however, deemed essential that the runtime cost of assertions be negligible if they are disabled. In order to achieve this with a library, the programmer is forced to hard-code each assertion as an if statement. Many programmers would not do this. Either they would omit the if statement and performance would suffer, or they would ignore the facility entirely. Note also that assertions were contained in James Gosling’s original specification for the Java programming language. Assertions were removed from the Oak specification because time constraints prevented a satisfactory design and implementation.
We considered providing such a facility, but were unable to convince ourselves that it is possible to graft it onto the Java programming language without massive changes to the Java platform libraries, and massive inconsistencies between old and new libraries. Further, we were not convinced that such a facility would preserve the simplicity that is the hallmark of the Java programming language. On balance, we came to the conclusion that a simple boolean assertion facility was a fairly straight-forward solution and far less risky. It’s worth noting that adding a boolean assertion facility to the language doesn’t preclude adding a full-fledged design-by-contract facility at some time in the future.
Providing such a construct would encourage programmers to put complex assertions inline, when they are better relegated to separate methods.
Compatibility
Yes, for source files. (Binaries for classes that use assert as an identifier will continue to work fine.) To ease the transition, we implemented a strategy whereby developers can continue using assert as an identifier during a transitional period.
Yes. Class files will contain calls to the new ClassLoader and Class methods, such as desiredAssertionStatus. If a class file containing calls to these methods is run against an older JRE (whose ClassLoader class doesn’t define the methods), the program will fail at run time, throwing a NoSuchMethodError. It is generally the case that programs using new facilities are not compatible with older releases.
Syntax and Semantics
The AssertionError Class
Access to these objects would encourage programmers to attempt to recover from assertion failures, which defeats the purpose of the facility.
This issue was controversial. The expert group discussed it at length, and came to the conclusion that Error was more appropriate to discourage programmers from attempting to recover from assertion failures. It is, in general, difficult or impossible to localize the source of an assertion failure. Such a failure indicates that the program is operating «outside of known space,» and attempts to continue execution are likely to be harmful. Further, convention dictates that methods specify most runtime exceptions they may throw (with @throws doc comments). It makes little sense to include in a method’s specification the circumstances under which it may generate an assertion failure. Such information may be regarded as an implementation detail, which can change from implementation to implementation and release to release.
Enabling and Disabling Assertions
It is a firm requirement that it be possible to enable assertions in the field, for enhanced serviceability. It would have been possible to also permit developers to eliminate assertions from object files at compile time. Assertions can contain side effects, though they should not, and such a flag could therefore alter the behavior of a program in significant ways. It is viewed as good thing that there is only one semantics associated with each valid Java program. Also, we want to encourage users to leave asserts in object files so they can be enabled in the field. Finally, the spec demands that assertions behave as if enabled when a class runs before it is initialized. It would be impossible to offer these semantics if assertions were stripped from the class file. Note, however, that the standard «conditional compilation idiom» described in the Java Language Specification can be used to achieve this effect for developers who really want it.
Hierarchical control is useful, as programmers really do use package hierarchies to organize their code. For example, package-tree semantics allow assertions to be enabled or disabled in all of Swing at one time.
No action (other than perhaps a warning message) is necessary or desirable if it’s too late to set the assertion status. An exception seems unduly heavyweight.
Clarity in method naming is for the greater good. Overloading tends to cause confusion.
It’s not clear that there would be any use for the resulting method. The method isn’t designed for application programmer use, and it seems inadvisable to make it slower and more complex than necessary.
While applets have no reason to call any of the ClassLoader methods for modifying assertion status, allowing them to do so seems harmless. At worst, an applet can mount a weak denial-of-service attack by enabling assertions in classes that have yet to be initialized. Moreover, applets can only affect the assert status of classes that are to be loaded by class loaders that the applets can access. There already exists a RuntimePermission to prevent untrusted code from gaining access to class loaders ( getClassLoader ).
Such a construct would encourage people to inline complex assertion code, which we view as a bad thing. Further, it is straightforward to query the assert status atop the current API, if you feel you must:
Few programmers are aware of the fact that a class’s constructors and methods can run prior to its initialization. When this happens, it is quite likely that the class’s invariants have not yet been established, which can cause serious and subtle bugs. Any assertion that executes in this state is likely to fail, alerting the programmer to the problem. Thus, it is generally helpful to the programmer to execute all assertions encountered while in this state.




