What does the Java assert keyword do, and when should it be used?

前端 未结 19 1507
眼角桃花
眼角桃花 2020-11-22 15:58

What are some real life examples to understand the key role of assertions?

相关标签:
19条回答
  • 2020-11-22 16:20

    Assertions are checks which may get switched off. They're rarely used. Why?

    • They must not be used for checking public method arguments as you have no control over them.
    • They should not be used for simple checks like result != null as such checks are very fast and there's hardly anything to save.

    So, what's left? Expensive checks for conditions really expected to be true. A good example would be the invariants of a data structure like RB-tree. Actually, in ConcurrentHashMap of JDK8, there are a few such meaningful asserts for the TreeNodes.

    • You really don't want to switch them on in production as they could easily dominate the run time.
    • You may want to switch them on or off during tests.
    • You definitely want to switch them on when working on the code.

    Sometimes, the check is not really expensive, but at the same time, you're pretty sure, it'll pass. In my code, there's e.g.,

    assert Sets.newHashSet(userIds).size() == userIds.size();
    

    where I'm pretty sure that the list I just created has unique elements, but I wanted to document and double check it.

    0 讨论(0)
  • 2020-11-22 16:21

    Let's assume that you are supposed to write a program to control a nuclear power-plant. It is pretty obvious that even the most minor mistake could have catastrophic results, therefore your code has to be bug-free (assuming that the JVM is bug-free for the sake of the argument).

    Java is not a verifiable language, which means: you cannot calculate that the result of your operation will be perfect. The main reason for this are pointers: they can point anywhere or nowhere, therefore they cannot be calculated to be of this exact value, at least not within a reasonable span of code. Given this problem, there is no way to prove that your code is correct at a whole. But what you can do is to prove that you at least find every bug when it happens.

    This idea is based on the Design-by-Contract (DbC) paradigm: you first define (with mathematical precision) what your method is supposed to do, and then verify this by testing it during actual execution. Example:

    // Calculates the sum of a (int) + b (int) and returns the result (int).
    int sum(int a, int b) {
      return a + b;
    }
    

    While this is pretty obvious to work fine, most programmers will not see the hidden bug inside this one (hint: the Ariane V crashed because of a similar bug). Now DbC defines that you must always check the input and output of a function to verify that it worked correctly. Java can do this through assertions:

    // Calculates the sum of a (int) + b (int) and returns the result (int).
    int sum(int a, int b) {
        assert (Integer.MAX_VALUE - a >= b) : "Value of " + a + " + " + b + " is too large to add.";
      final int result = a + b;
        assert (result - a == b) : "Sum of " + a + " + " + b + " returned wrong sum " + result;
      return result;
    }
    

    Should this function now ever fail, you will notice it. You will know that there is a problem in your code, you know where it is and you know what caused it (similar to Exceptions). And what is even more important: you stop executing right when it happens to prevent any further code to work with wrong values and potentially cause damage to whatever it controls.

    Java Exceptions are a similar concept, but they fail to verify everything. If you want even more checks (at the cost of execution speed) you need to use assertions. Doing so will bloat your code, but you can in the end deliver a product at a surprisingly short development time (the earlier you fix a bug, the lower the cost). And in addition: if there is any bug inside your code, you will detect it. There is no way of a bug slipping-through and cause issues later.

    This still is not a guarantee for bug-free code, but it is much closer to that, than usual programs.

    0 讨论(0)
  • 2020-11-22 16:21

    An assertion allows for detecting defects in the code. You can turn on assertions for testing and debugging while leaving them off when your program is in production.

    Why assert something when you know it is true? It is only true when everything is working properly. If the program has a defect, it might not actually be true. Detecting this earlier in the process lets you know something is wrong.

    An assert statement contains this statement along with an optional String message.

    The syntax for an assert statement has two forms:

    assert boolean_expression;
    assert boolean_expression: error_message;
    

    Here are some basic rules which govern where assertions should be used and where they should not be used. Assertions should be used for:

    1. Validating input parameters of a private method. NOT for public methods. public methods should throw regular exceptions when passed bad parameters.

    2. Anywhere in the program to ensure the validity of a fact which is almost certainly true.

    For example, if you are sure that it will only be either 1 or 2, you can use an assertion like this:

    ...
    if (i == 1)    {
        ...
    }
    else if (i == 2)    {
        ...
    } else {
        assert false : "cannot happen. i is " + i;
    }
    ...
    
    1. Validating post conditions at the end of any method. This means, after executing the business logic, you can use assertions to ensure that the internal state of your variables or results is consistent with what you expect. For example, a method that opens a socket or a file can use an assertion at the end to ensure that the socket or the file is indeed opened.

    Assertions should not be used for:

    1. Validating input parameters of a public method. Since assertions may not always be executed, the regular exception mechanism should be used.

    2. Validating constraints on something that is input by the user. Same as above.

    3. Should not be used for side effects.

    For example this is not a proper use because here the assertion is used for its side effect of calling of the doSomething() method.

    public boolean doSomething() {
    ...    
    }
    public void someMethod() {       
    assert doSomething(); 
    }
    

    The only case where this could be justified is when you are trying to find out whether or not assertions are enabled in your code:   

    boolean enabled = false;    
    assert enabled = true;    
    if (enabled) {
        System.out.println("Assertions are enabled");
    } else {
        System.out.println("Assertions are disabled");
    }
    
    0 讨论(0)
  • 2020-11-22 16:23

    Assertions are a development-phase tool to catch bugs in your code. They're designed to be easily removed, so they won't exist in production code. So assertions are not part of the "solution" that you deliver to the customer. They're internal checks to make sure that the assumptions you're making are correct. The most common example is to test for null. Many methods are written like this:

    void doSomething(Widget widget) {
      if (widget != null) {
        widget.someMethod(); // ...
        ... // do more stuff with this widget
      }
    }
    

    Very often in a method like this, the widget should simply never be null. So if it's null, there's a bug in your code somewhere that you need to track down. But the code above will never tell you this. So in a well-intentioned effort to write "safe" code, you're also hiding a bug. It's much better to write code like this:

    /**
     * @param Widget widget Should never be null
     */
    void doSomething(Widget widget) {
      assert widget != null;
      widget.someMethod(); // ...
        ... // do more stuff with this widget
    }
    

    This way, you will be sure to catch this bug early. (It's also useful to specify in the contract that this parameter should never be null.) Be sure to turn assertions on when you test your code during development. (And persuading your colleagues to do this, too is often difficult, which I find very annoying.)

    Now, some of your colleagues will object to this code, arguing that you should still put in the null check to prevent an exception in production. In that case, the assertion is still useful. You can write it like this:

    void doSomething(Widget widget) {
      assert widget != null;
      if (widget != null) {
        widget.someMethod(); // ...
        ... // do more stuff with this widget
      }
    }
    

    This way, your colleagues will be happy that the null check is there for production code, but during development, you're no longer hiding the bug when widget is null.

    Here's a real-world example: I once wrote a method that compared two arbitrary values for equality, where either value could be null:

    /**
     * Compare two values using equals(), after checking for null.
     * @param thisValue (may be null)
     * @param otherValue (may be null)
     * @return True if they are both null or if equals() returns true
     */
    public static boolean compare(final Object thisValue, final Object otherValue) {
      boolean result;
      if (thisValue == null) {
        result = otherValue == null;
      } else {
        result = thisValue.equals(otherValue);
      }
      return result;
    }
    

    This code delegates the work of the equals() method in the case where thisValue is not null. But it assumes the equals() method correctly fulfills the contract of equals() by properly handling a null parameter.

    A colleague objected to my code, telling me that many of our classes have buggy equals() methods that don't test for null, so I should put that check into this method. It's debatable if this is wise, or if we should force the error, so we can spot it and fix it, but I deferred to my colleague and put in a null check, which I've marked with a comment:

    public static boolean compare(final Object thisValue, final Object otherValue) {
      boolean result;
      if (thisValue == null) {
        result = otherValue == null;
      } else {
        result = otherValue != null && thisValue.equals(otherValue); // questionable null check
      }
      return result;
    }
    

    The additional check here, other != null, is only necessary if the equals() method fails to check for null as required by its contract.

    Rather than engage in a fruitless debate with my colleague about the wisdom of letting the buggy code stay in our code base, I simply put two assertions in the code. These assertions will let me know, during the development phase, if one of our classes fails to implement equals() properly, so I can fix it:

    public static boolean compare(final Object thisValue, final Object otherValue) {
      boolean result;
      if (thisValue == null) {
        result = otherValue == null;
        assert otherValue == null || otherValue.equals(null) == false;
      } else {
        result = otherValue != null && thisValue.equals(otherValue);
        assert thisValue.equals(null) == false;
      }
      return result;
    }
    

    The important points to keep in mind are these:

    1. Assertions are development-phase tools only.

    2. The point of an assertion is to let you know if there's a bug, not just in your code, but in your code base. (The assertions here will actually flag bugs in other classes.)

    3. Even if my colleague was confident that our classes were properly written, the assertions here would still be useful. New classes will be added that might fail to test for null, and this method can flag those bugs for us.

    4. In development, you should always turn assertions on, even if the code you've written doesn't use assertions. My IDE is set to always do this by default for any new executable.

    5. The assertions don't change the behavior of the code in production, so my colleague is happy that the null check is there, and that this method will execute properly even if the equals() method is buggy. I'm happy because I will catch any buggy equals() method in development.

    Also, you should test your assertion policy by putting in a temporary assertion that will fail, so you can be certain that you are notified, either through the log file or a stack trace in the output stream.

    0 讨论(0)
  • 2020-11-22 16:27

    Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea option on the java command, but are not turned on by default.

    An example:

    public Foo acquireFoo(int id) {
      Foo result = null;
      if (id > 50) {
        result = fooService.read(id);
      } else {
        result = new Foo(id);
      }
      assert result != null;
    
      return result;
    }
    
    0 讨论(0)
  • 2020-11-22 16:27

    Assert is very useful when developing. You use it when something just cannot happen if your code is working correctly. It's easy to use, and can stay in the code for ever, because it will be turned off in real life.

    If there is any chance that the condition can occur in real life, then you must handle it.

    I love it, but don't know how to turn it on in Eclipse/Android/ADT . It seems to be off even when debugging. (There is a thread on this, but it refers to the 'Java vm', which does not appear in the ADT Run Configuration).

    0 讨论(0)
提交回复
热议问题