Java assertions underused

前端 未结 11 2122
独厮守ぢ
独厮守ぢ 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:45

    Assertions are useful because they:

    • catch PROGRAMMING errors early
    • document code using code

    Think of them as code self-validation. If they fail it should mean that your program is broken and must stop. Always turn them on while unit testing !

    In The Pragmatic Programmer they even recommend to let them run in production.

    Leave Assertions Turned On

    Use Assertions to Prevent the Impossible.

    Note that assertions throw AssertionError if they fail, so not caught by catch Exception.

提交回复
热议问题