Guava preconditions checkNull, checkArgument

前端 未结 1 1564
面向向阳花
面向向阳花 2021-01-21 15:24

I want to check preconditions on a base class so that I know subtypes will always use constructor arguments that are valid.

Let\'s take as an example a constructor that:

1条回答
  •  北海茫月
    2021-01-21 16:12

    This should have been a comment, but it's too long.

    • Calling super before the test is harmless provided that the super ctor doesn't do things which it shouldn't do anyway.
    • It could be prevented via a static builder method, you need no Builder. But it's not worth it.
    • I doubt that grouping tests is generally useful; if it was, then there would be a such method already. But if you need one such a concrete thing more than twice, then write your own; if it comes often, report it to the Guava team as an RFE.
    • I'm pretty sure, matchers are an overkill here as you're just creating an exception, i.e., something used only rarely (I hope). As your test is runtime only, it can't really help to catch errors. It would be nice, if you could statically ensure a "properly" constructed exception, but it's impossible in pure java.

    More important: The exceptions you're throwing are probably inferior to the ones you'd get without all the checks. Imagine the user provides a cause and no message. That's bad, you think, but you replace it with an NPE lacking any cause. That's worse.

    Look at Guava's Preconditions.format (package private). They could check the correct number of arguments first, but they do not. You can provide too few or too many, which is an error, but ignoring it is the best way to handle it.

    0 讨论(0)
提交回复
热议问题