Use assertion to improve your code reliability

xiaoxiao2021-03-06  44

The following is some examples of using Assertions and their corresponding examples, which allow the Java program more reliable.

First, check the control flow; in the if-dam-else and swith-case statements, we can add the Assert False statement on the control tribunition that should not occur. If this happens, Assert can check it out. For example: X value can only make 1, 2, 3, and our program can be said

Switch (x) {casse 1: ...; case 2: ...; case 3: ... default: assert false: "x value is invalid:" x;}

Second, before the private function calculation, check if the input parameter is valid; for some other functions, require input to meet some specific conditions, then we can use Assert to use Assert to check the parameter check at the beginning of the function. For public functions, we usually do not use Assertion check, because in general, public functions must check and process invalid parameters. And private functions are often used directly. For example, a function may require input parameters to be NULL. Then we can add Assert Parameter1! = Null: "Paramerter is null in test method"; Third, after the function calculation, check if the function result is valid; for some calculation functions, some of the function runs The value needs to ensure a certain nature, so we can check this value via Assert. For example, we have a function of calculating the wrong value, then we can at the results of the function, plus a statement: assert value> = 0: "Value Should Be Bigger Than 0:" value; In this way, we The result of the function calculates can be checked. Fourth, check the program is not variable; some of the programs, there are some invariant, and these invariant values ​​are unchanged in the run life cycle of the program. These invariance may be a simple expression or a complex expression. For some key non-variables, we can check them via Assert. For example, in a financial system, the company's spending and income must maintain a certain balance relationship, so we can write an expression to check this balance relationship, as follows.

Private Boolean Isbalance () {...} In this system, we can add Assert isbalance (): assert isbalance (): "balance is destoried" in this system.

转载请注明原文地址:https://www.9cbs.com/read-82645.html

New Post(0)