Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which line is an inappropriate use of an assertion?

public class Sample10
{
    private int half(int n)
    {
        assert n % 2 == 0 : n;
        return n / 2;
    }

    public int halveEven(int n)
    {
        assert n % 2 == 0 : n;
        return half(n);
    }
}

  • A.Neither; both are appropriate.
  • B.The assertion inside halveEven, because that method is public
  • C.The assertion inside half, because that method is private
  • D.Both assertions, because a value is used as a detail message

Answer: B

The check inside the private half() is exactly the endorsed use: confirming an invariant the class controls. The identical check inside the public halveEven() is not, because callers outside the class rely on that restriction and it vanishes when assertions are disabled. Only the public one needs an explicit throw.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.