Help you debug-java1.4-assertions. Assertions make your code more stable.

Source: Internet
Author: User
Tags xsl
Use assertions to make your code more stable


Learn how Java's assertions (assertions) performance provides developers with a better way to create stable, high-quality, and easy-to-Debug code.
By josh Street

Perhaps you have not noticed that Sun Microsystems has added a new keyword to the Java language. ThisAssertThe keyword is proposed by jsr41-a Java specification request that finally adds the real assertions performance to Java. Because of this newAssertThe keyword is very different from the usage that most C/C ++ developers are familiar with, so understanding it in detail will certainly benefit you.

The assertions feature of Java is used for a special purpose: when the user-defined Boolean expression is false, it throws an error. More specifically, an assertion is used as a signal to discover that a value changes to false, which indicates that the current function needs to be interrupted. This performance is useful when creating a dedicated debugging mode that shouldn't appear in the real product deployment process.

Enable assertion
Before using assertions, You Need To enable them Because Java Runtime Environment (JRE) will automatically disable all assertions. You can use-EnableassertionsFlag-Ea).-DisableassertionsMark (abbreviated-Da) To close it. You can use some options with both tags:

  • No argumentsIndicates that the flag applies to all assertions.
  • Packagename...Indicates that this tag appliesPackagenameAll classes in the package and its sub-packages.
  • ...This tag applies to Untitled (default) packages in the current directory.
  • ClassnameIndicates that the flag only appliesClassname.
  • See the following command line:

    java -ea:foo.bar... -da:foo.bar.old MyClass

    It is used to enable assertions in the foo. Bar package and its subdirectories except Foo. Bar. Old.

    How and when to use assertion
    A Java assertion has two forms. The first form has been proven to be desirable:

    assert some_boolean_expression;

    This means that ifSome_boolean_expressionIf the value is false, an assertionerror is thrown. Note that this is an error rather than an exception. Similarly, it is treated as an unchecked exception. (For more information about the differences between errors and exceptions, see my other article "errors and exceptions ".)

    Another more complex formAssertStatements provide more functions:

    assert some_boolean_expression :    some_non-void_expression

    This form is more useful than the previous one. Second expressionSome_non-void_expressionIt is passed in to the constructor for assertionerror. It displays more information when the assertion fails. Note that the second parameter may be any object or basic type (including null ).

    List 1 provides a simple way to use the secondAssertExample of statement form. Assertionerror is a non-check exception, so it is not necessary to capture it (in List 1 it is captured for the reasons described in the demonstration ). In fact, ignoring (not capturing) assertionerrors may seem quite good, but you should not, because it may make the application in an unstable state, this is especially true for a swing-based program.

    There are some situations where assertions cannot be used, such as trying to locate the problem using the following code:

    assert isValid( myObject );

    Although this seems like a good way to do this, think about what to do when assertion is disabled-remember that this is its default state: ThisIsvalidThe method cannot be executed! In particular, some actions (methods, operations, and so on) cannot be used for thisAssertThe first parameter of the statement, because (unless otherwise specified) it will never be executed.

    You may want to know how to compile the code to enable assertions. Although this is not a good idea, it will be helpful for known dependency code. Sun provides the following tips:

        boolean assertsEnabled = false;      // here's the trick       assert assertsEnabled = true;    if( !assertsEnabled )        throw new RuntimeException(           "Asserts must be enabled!");}

    You can use this code in any static initialization class to enable assertion. If assertion is disabledAssertThe statement cannot be executed and an exception is thrown; otherwise, the statement continues and the condition becomes invalid.

    Solve compatibility issues
    Java's assertion function is a language feature, not an extension of API performance. Assertions represents the first significant change in the Java language between multiple versions, but it also brought back the problem of binary compatibility. This means that the program compiled to support assertions will not be able to run in the old version of JRE. Sun took caution to make it easier for developers to create programs with assertions. In JDK 1.4, the default state of a program does not support assertion. The Code Compiled with assertions will generate the following response:

    warning: as of release 1.4, assert is a keyword, and may not be used as an identifier

    In addition to this warningAssertKeyword may also cause many compilation errors. To compile the program using assertions, you need to use-Source1.4 mark. For example, the compilation command code displayed in List 1 is as follows:

    javac -source 1.4 Assert.java

    The new Java assertion function provides developers with new methods to use advanced technologies (such as design by contract) to create stable and high-quality code. You need to consider the issues I mentioned, but I think you will agree that this new feature is quite popular in Java.

    -- List 1 ---.

    Use assert for Detection

    List 1. This simple example demonstrates how to use assertions to detect predictable but unsatisfactory results.

    public class Assert{   public static void main(String[] args)   {      try      {         doSomething();      }      catch(AssertionError error)      {         error.printStackTrace();      }   }   public static int doSomething()   {      int i = 2;      assert i != 2 : "i was 2 for some reason";      return i;   }}


    About Author:
    Josh Street is a Solution Architect for Bank of America. You can contact him via rjstreet@computer.org.

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.