Assert a good practice or not?

前端 未结 7 1349
礼貌的吻别
礼貌的吻别 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条回答
  •  猫巷女王i
    2021-01-30 05:42

    Yes it is good practice.

    In the Spring case, it is particularly important because the checks are validating property settings, etc that are typically coming from XML wiring files. In other words, they are validating the webapp's configuration. And if you ever do any serious Spring-based development, those validation checks will save you hours of debugging when you make a silly configuration mistake.

    But note that there is a BIG difference between a library class called Assert and the Java assert keyword which is used to define a Java assertion. The latter form of assertions can be turned off at application launch time, and should NOT be used for argument validation checks that you always want to happen. Clearly, the Spring designers think it would be a really bad idea to turn off webapp configuration sanity checks ... and I agree.

    UPDATE

    In Java 7 (and later) the java.util.Objects class provides a requireNonNull convenience method to test if an argument is null and raise an exception. You use it like this:

     SomeType t = ...
     SomeType tChecked = Objects.requireNonNull(t);
    

    or

     SomeType tChecked = Objects.requireNonNull(t, "t should be non-null");
    

    However, note that this method raises NullPointerException rather than IllegalArgumentException.

提交回复
热议问题