Thursday, September 15, 2005

Assertions


Do not use assertions to validate arguments to a public method

Do use assertions to validate arguments to a private method

Please explain the difference between them?


Create two different classes namely General and CheckAssert.


public class General {

public static void main(String[] args) {

CheckAssert ca = new CheckAssert();

ca.call(0);

}

}


public class CheckAssert {

private void call(int i) {

assert (i>0);

System.out.println(i);

}

/*

public void call(int i) {

assert (i>0);

System.out.println(i);

}

Do not use assertions to validate arguments to a public method

*/

}

and compile

javac -source 1.4 CheckAssert.java

javac General.java


and execute

java -ea General

o/p

Exception in thread "main" java.lang.AssertionError

at CheckAssert.call(CheckAssert.java:4)

at General.main(General.java:5)


java General

o/p

0


A public method might be called from code that you don't control. Because public methods are part of your exposed interface to the outside world. You are supposed to guarantee that any constraints on the arguments will be enforced by the method itself. But since assertions aren't guaranteed to actually run( they are typically disabled in a deployed applications), the enforcement won't happen if assertions aren't enabled. You don't want publicly accessible code that works only conditionally, depending on whether assertions are enabled (or) disabled.

If you need to validate public method arguments you will probably use exceptions to throw, say IllegalArgumentException if the values passed to the public method are invalid.



0 Comments:

Post a Comment

<< Home