Java assertions underused

前端 未结 11 2124
独厮守ぢ
独厮守ぢ 2020-12-04 21:16

I\'m wondering why the assert keyword is so underused in Java? I\'ve almost never seen them used, but I think they\'re a great idea. I certainly much prefer the

11条回答
  •  孤城傲影
    2020-12-04 21:39

    It's an abuse of assertions to use them to test user input. Throwing an IllegalArgumentException on invalid input is more correct, as it allows the calling method to catch the exception, display the error, and do whatever it needs to (ask for input again, quit, whatever).

    If that method is a private method inside one of your classes, the assertion is fine, because you are just trying to make sure you aren't accidentally passing it a null argument. You test with assertions on, and when you have tested all the paths through and not triggered the assertion, you can turn them off so that you aren't wasting resources on them. They are also useful just as comments. An assert at the start of a method is good documentation to maintainers that they should be following certain preconditions, and an assert at the end with a postcondition documents what the method should be doing. They can be just as useful as comments; moreso, because with assertions on, they actually TEST what they document.

    Assertions are for testing/debugging, not error-checking, which is why they are off by default: to discourage people from using assertions to validate user input.

提交回复
热议问题