Java assertions underused

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

    As others have stated: assertions are not appropriate for validating user input.

    If you are concerned with verbosity, I recommend you check out a library I wrote: https://github.com/cowwoc/requirements.java/. It'll allow you to express these checks using very little code, and it'll even generate the error message on your behalf:

    requireThat("name", value).isNotNull();
    

    and if you insist on using assertions, you can do this too:

    assertThat("name", value).isNotNull();
    

    The output will look like this:

    java.lang.NullPointerException: name may not be null
    

提交回复
热议问题