What does the Java assert keyword do, and when should it be used?

前端 未结 19 1724
眼角桃花
眼角桃花 2020-11-22 15:58

What are some real life examples to understand the key role of assertions?

19条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 16:20

    Assertions are checks which may get switched off. They're rarely used. Why?

    • They must not be used for checking public method arguments as you have no control over them.
    • They should not be used for simple checks like result != null as such checks are very fast and there's hardly anything to save.

    So, what's left? Expensive checks for conditions really expected to be true. A good example would be the invariants of a data structure like RB-tree. Actually, in ConcurrentHashMap of JDK8, there are a few such meaningful asserts for the TreeNodes.

    • You really don't want to switch them on in production as they could easily dominate the run time.
    • You may want to switch them on or off during tests.
    • You definitely want to switch them on when working on the code.

    Sometimes, the check is not really expensive, but at the same time, you're pretty sure, it'll pass. In my code, there's e.g.,

    assert Sets.newHashSet(userIds).size() == userIds.size();
    

    where I'm pretty sure that the list I just created has unique elements, but I wanted to document and double check it.

提交回复
热议问题