Example : java -ea TestAssertionClass
Also when ever we want to deploy application that time we can disable Assertions using [-da or -disableassertions].
Example : java -da TestAssertionClass
An assertion is a statement in the JavaTM 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.
Practical Example :
Code:
//Old Technique without assertation
private void methodA(int num) {
useNum(num + x); // we've tested this;
// we now know we're good here
}
//New Technique with assertation
private void methodA(int num) {
assert (num>=0); // throws an AssertionError
// if this test isn't true
useNum(num + x);
}
General Questions
General Questions
Why provide an assertion facility, given that one can program assertions atop the Java programming language with no special support?
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.- Why does this facility justify a language change, as opposed to a library solution?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. - Why not provide a full-fledged design-by-contract facility with preconditions, postconditions and class invariants, like the one in the Eiffel programming language?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.
The simple assertion facility does enable a limited form of design-by-contract style programming. Theassert
statement is appropriate for nonpublic precondition, postcondition and class invariant checking. Public precondition checking should still be performed by checks inside methods that result in particular, documented exceptions, such asIllegalArgumentException
andIllegalStateException
. - In addition to boolean assertions, why not provide an assert-like construct to suppress the execution of an entire block of code if assertions are disabled?Providing such a construct would encourage programmers to put complex assertions inline, when they are better relegated to separate methods.
Compatibility
- Won't the new keyword cause compatibility problems with existing programs that use
assert
as an identifier?Yes, for source files. (Binaries for classes that useassert
as an identifier will continue to work fine.) To ease the transition, we implemented a strategy whereby developers can continue usingassert
as an identifier during a transitional period. - Doesn't this facility produce class files that cannot be run against older JREs?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 (whoseClassLoader 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
- Why allow primitive types in Expression2?There is no compelling reason to restrict the type of this expression. Allowing arbitrary types provides convenience for developers who, for example, want to associate a unique integer code with each assertion. Further, it makes this expression feel like the argument of
System.out.println(...)
, which is seen as desirable.
The AssertionError Class
- When an
AssertionError
is generated by an assert statement in which Expression2 is absent, why isn't the program text of the asserted condition used as the detail message (for example," )?While doing so might improve out-of-the-box usefulness of assertions in some cases, the benefit doesn't justify the cost of adding all those string constants toheight < maxHeight
".class
files and runtime images. - Why doesn't an
AssertionError
allow access to the object that generated it? Similarly, why not pass an arbitrary object from the assertion to theAssertionError
constructor in place of a detail message?Access to these objects would encourage programmers to attempt to recover from assertion failures, which defeats the purpose of the facility. - Why not provide context accessors (like
getFile
,getline
,getMethod
) onAssertionError
?This facility is best provided onThrowable
, so it may be used for all throwables, not just just assertion errors. We enhancedThrowable
with thegetStackTrace
method to provide this functionality. - Why is
AssertionError
a subclass ofError
rather thanRuntimeException
?This issue was controversial. The expert group discussed it at at length, and came to the conclusion thatError
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
- Why not provide a compiler flag to completely eliminate assertions from object files?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 JLS 14.20 can be used to achieve this effect for developers who really want it.
- Why do the commands that enable and disable assertions use package-tree semantics instead of the more traditional package semantics?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.
- Why does
setClassAssertionStatus
return aboolean
instead of throwing an exception if it is invoked when it's too late to set the assertion status (that is, if the named class has already been initialized)?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. - Why not overload a single method name to take the place of
setDefaultAssertionStatus
andsetAssertionStatus
?Clarity in method naming is for the greater good. Overloading tends to cause confusion. - Why not tweak the semantics of desiredAssertionStatus to make it more "programmer friendly" by returning the actual assertion status if a class is already initialized?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.
- Why is there no
RuntimePermission
to prevent applets from enabling/disabling assertions?While applets have no reason to call any of theClassLoader
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 aRuntimePermission
to prevent untrusted code from gaining access to class loaders (getClassLoader
). - Why not provide a construct to query the assert status of the containing class?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:
boolean assertsEnabled = false; assert assertsEnabled = true; // Intentional side-effect!!! // Now assertsEnabled is set to the correct value
- Why does an assert statement that executes before its class is initialized behave as if assertions were enabled in the class? 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.
No comments:
Post a Comment
I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.