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
Those asserts are library-supplied and are not the same as the built-in assert
keyword.
There's a difference here: assert
s 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.