Assert of "151 Suggestions for Improving Java Programs" Reading Notes

Recommendation 19: Assertions are definitely not tasteless
. In defensive programming, assertions are often used to judge parameters and environments to avoid
logic exceptions caused by improper input or wrong environments. Assertions exist in many languages. C, C++, Python all have different
assertion representations. The assertion in Java uses the assert keyword, and its basic usage is as follows:
assert <Boolean expression>
assert <Boolean expression>: <Error information>
When the Boolean expression is false, an AssertionError error is thrown, and the accompanying error message. The syntax of assert is relatively
simple and has the following two characteristics:
(1) assert is not enabled by default.
We know that assert is for debugging programs, and the purpose is to detect program exceptions quickly and easily, but
this document is a very fast PDF The editor is generated.
If you want to remove this prompt, please visit and download:
http://www.jisupdfeditor.com/
2017/10/20
46/396
Java is not enabled by default. To enable it, you need to compile, Add related keywords at runtime, this is not much
to say, if necessary, you can refer to the Java specification.
(2) The exception AssertionError thrown by assert is an assertion inherited from Error.
After the assertion fails, the JVM will throw an AssertionError error, which inherits from Error. Note that this is an
error that is unrecoverable, which means that this is an error. Serious problems, developers must pay attention to and solve them.
Although assert is an assertion, it cannot be equivalent to a conditional judgment such as if...else.... It
cannot be used in the following two situations: (1) We know that defensive programming is the core
of the methods exposed to the outside world.
The point is: all external factors (input parameters, environment variables,
context ) are "evil", and there is a source of evil that attempts to destroy the program. In order to resist it, we have to
test everywhere in the program, everywhere. If the card is set, the subsequent program will not be executed if the conditions are not met, so as to protect the correctness of the main program. There is no
problem with setting the card everywhere, but the assertion cannot be used for input verification, especially the public method. Let's look at an example:
public class Client{
        public static void main
( String[]args ) {
        StringUtils.encode
( null );
        }}
//
String processing tool
class StringUtils{
public static String encode
( String str ) {
assert str
! =null : "The encrypted string is null" ;
/* Encryption processing */
} }
The encode method assumes that the input parameter is not empty, if it is empty, it will throw an AssertionError, but
there is a serious problem in this program, encode is a public method, this sign Because it is open to the public, any
class can be called as long as it can pass a parameter of type String (complying with the contract), but the Client class calls the enocde method according to the
specification and contract, but gets an AssertionError error message, who destroyed it contract agreement?
— is the encode method itself.
This document is generated by the extremely fast PDF editor.
If you want to remove this prompt, please visit and download:
http://www.jisupdfeditor.com/
2017/10/20
47/396 (2)
assert in the case of executing logic code
Support is optional, it can be run in development, but it is not needed in production
(in order to improve performance), so logic code cannot be executed in the boolean expression of assert, otherwise it will be different depending
on the environment. Produces different logic like:
public void doSomething ( List list, Object element ) {
assert list.remove
( element ): " 删除元素 "+element+" 失败 "
/* 业务处理 */
}
这段代码在assert启用的环境下,没有任何问题,但是一旦投入到生产环境,就不会启
用断言了,而这个方法也就彻底完蛋了,list的删除动作永远都不会执行,所以也就永远不
会报错或异常,因为根本就没有执行嘛!
以上两种情况下不能使用assert,那在什么情况下能够使用assert呢?一句话:按照正
常执行逻辑不可能到达的代码区域可以放置assert。具体分为三种情况:
(1)在私有方法中放置assert作为输入参数的校验
在私有方法中可以放置assert校验输入参数,因为私有方法的使用者是作者自己,私有
方法的调用者和被调用者之间是一种弱契约关系,或者说没有契约关系,其间的约束是依靠
作者自己控制的,因此加上assert可以更好地预防自己犯错,或者无意的程序犯错。
(2)流程控制中不可能达到的区域
这类似于JUnit的fail方法,其标志性的意义就是:程序执行到这里就是错误的,例
如:
public void doSomething () {
int i=7

while i 7 {
/*
业务处理 */
}
assert false
" 到达这里就表示错误 "
}
该文档是极速PDF编辑器生成,
如果想去掉该提示,请访问并下载:
http://www.jisupdfeditor.com/
2017/10/20
48/396
(3)建立程序探针
我们可能会在一段程序中定义两个变量,分别代表两个不同的业务含义,但是两者有固
定的关系,例如var1=var2*2,那我们就可以在程序中到处设“桩”,断言这两者的关系,
如果不满足即表明程序已经出现了异常,业务也就没有必要运行下去了。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325849251&siteId=291194637