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

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

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

19条回答
  •  一向
    一向 (楼主)
    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");
    }
    

提交回复
热议问题