Friday, May 11, 2007

Explain Assertions with a code example

The main reason of introducing assertions in Java from R1.4 onwards is to reduce the chances of bugs which otherwise would have gone unnoticed, in one's code.In fact, finding and removing bugs is one tedious and not so exciting task.Assertions should be used for scenarios which ideally should never happen in the lifecycle of a program,check assumptions about data structures (such as ensuring that an array is of the correct length), or enforcing constraints on arguments of private methods.Assertions help in a way to block these bugs at the beginning of writing actual logic inside your code that saves lot of efforts,time and most significantly, costs.A simple assertion facility provides a limited form of design-by-contract programming.In design-by-contract programming identification of preconditions and post conditions to a program are must before even starting the coding itself.

Here is simple Java code which uses assertions, here the task is to determine the gender of a person.We have used a switch-case statement to define the over all flow of the logic :


Use J2SE 1.4.x (or later versions) to compile ExampleAssertions, make sure you use the -source option as follows:

javac -source 1.4 ExampleAssertions.java

If you try to compile your assertion-enabled classes without using the -source 1.4 option, you will get a compiler error saying that assert is a new keyword as of release 1.4. If you now run the program using the command and you enter a valid character, it will work fine. However, if you enter an invalid character, nothing will happen.

This is because, by default, assertions are disabled at runtime.You have to enable assertions to make them work.Use the switch -enableassertion (or -ea) as follows:

java -ea ExampleAssertions
java -enableassertion ExampleAssertions

Following is a sample run:






When assertion fails it throws AssertionError.By default assertions are disabled but once enabled and you wnat to disable them then use switch -diableassertion (or -da).

Diabling assertions for a particular class in a package:

java -da:com.punsoft.acc.Account SavingAccount , this means running class SavingAccount with assertions of Account class disabled.

java -da:com.punsoft.acc... SavingAccount, this means running class SavingAccount with assertions of 'acc' package and its subpackages disabled.

You can use combination of enable and disable assertions.

java -ea:com.punsoft.acc... -da:com.punsoft.view.acc SavingAccountView

If you use the command
java -ea SavingAccount

then assertions are enabled in all classes except system classes. If you wish to turn assertions on or off in system classes, use the switches -enablesystemassertions (or -esa) and -disablesystemassertions (or -dsa).

0 comments :

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker