Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using assertion in main() method

Here is a question I'm trying to answer:

Which of the following use assertions appropriately?

public class Hunt {
  public static void main(String... args) {
      int y = 10;
      assert y > 5; // #1
      new Hunt().netant(y);
  }

  public void netant(int x) {
      assert x > 0; // #2
      anteater(x);
  }

  private void anteater(int x) {
      assert x > 0; // #3
  }
}

Choose: 2

Options:

  1. #1
  2. #2
  3. #3
  4. The program has runtime errors although assertions are used correctly

Correct Answer: 1 & 3

Explanation: It is not advisable to use assertions to assert arguments of public methods

Source:http://www.certpal.com

The answer states "It is not advisable to use assertions to assert arguments of public methods". But in the above code even though assert statement is used to assert arguments of main() method it is chosen as the right answer!

Is it advisable to use assert statement in main() method?

like image 427
KuldeepBB Avatar asked Oct 26 '25 07:10

KuldeepBB


1 Answers

Assertions are a defence mechanism for coding errors. Entering an invalid argument in to a public method is a user error, even if it's an API a programmer is using.

Users should never see an assert, tests should.

like image 87
Tony Hopkinson Avatar answered Oct 28 '25 21:10

Tony Hopkinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!