Java Maintaining Program Correctness with Assertions - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Java Maintaining Program Correctness with Assertions - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, December 24, 2018

Java Maintaining Program Correctness with Assertions

Java Maintaining Program Correctness with Assertions

Problem

You want to leave tests in your code but not have runtime checking overhead until
you need it.

Solution

Use the JDK 1.4 Assertions mechanism.

Explained

JDK 1.4 introduced a new keyword into the language: assert . The assert keyword
takes two arguments separated by a colon (by analogy with the conditional operator):
an expression that is asserted by the developer to be true, and a message to be
included in the exception that is thrown if the expression is false. To provide for back-
ward compatibility with programs that might have used “assert” as an identifier name
on prior JDK versions, JDK 1.4 requires a command-line switch ( -source 1.4 ) that
must be provided for assert to be recognized as a keyword. Normally, assertions are
meant to be left in place (unlike quick and dirty print statements, which are often put
in during one test and then removed). To reduce runtime overhead, assertion check-
ing is not enabled by default; it must be enabled explicitly with the -enableassertions
(or -ea ) command-line flag. Here is a simple demo program that shows the use of the
assertion mechanism:


public class AssertDemo {
public static void main(String[] args) {
int i = 4;
if (args.length == 1) {
i = Integer.parseInt(args[0]);
}
assert i > 0 : "i is non-positive";
System.out.println("Hello after an assertion");
}
}

No comments:

Post a Comment

Post Top Ad