Assert a good practice or not?

前端 未结 7 1337
礼貌的吻别
礼貌的吻别 2021-01-30 05:02

Is it a good practice to use Assert for function parameters to enforce their validity. I was going through the source code of Spring Framework and I noticed that they use

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 05:46

    Those asserts are library-supplied and are not the same as the built-in assert keyword.

    There's a difference here: asserts do not run by default (they must be enabled with the -ea parameter), while the assertions provided by the Assert class cannot be disabled.

    In my opinion (for what it's worth), this is as good a method as any for validating parameters. If you had used built-in assertions as the question title implies, I would have argued against it on the basis that necessary checks should not be removable. But this way is just shorthand for:

    public static ParsedSql parseSqlStatement(String sql) {
        if (sql == null)
            throw new IllegalArgumentException("SQL must not be null");
        ...
    }
    

    ... which is always good practice to do in public methods.

    The built-in style of asserts is more useful for situations where a condition should always be true, or for private methods. The language guide introducing assertions has some good guidelines which are basically what I've just described.

提交回复
热议问题