In this article I’ll give a detailed explanation of the use of Assertions in Java. Assertion often confuse the programmer. It so happens that a programmer is confused as to which of the following to use: IF / ELSE or Assertions?. Assertions are basically used to test whether your code is according to the rules without making use of looping. It just tests the correctness of your code. Assertions are used ONLY and ONLY to in development environment. When the software/code goes to production, they should be removed without affecting the flow of the code. So be sure to implement assert such that the code is not dependent on it, so that later you can remove it without changing the logic of the code. If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.
The syntax to use of Assertions can be categorized as follows:
- assert Expression;
- assert Expression1: Expression2;
An assert should always have a value of True, otherwise it will raise an exception AssertionError.
- In the first syntax, the expression is tested only if the out of the expression is True, else an exception is “raised”.
- In the second syntax, a second expression (Expression2) serves as a message to the programmer to see what is happening.
also read:
- What is the difference between JRE,JVM and JDK?
- What is transient keyword in Java?
- JUnit 4.0 Example
Using Assertion in Practice
Let’s check an example below to understand assertion. The example used here is from the Oracle documentation, to facilitate understanding.
Imagine the following situation: You have developed a software that calculates the velocity of particles, and you know that this speed must be less than the speed of light. For the purpose of knowing the speed of light is approximately: 300 thousand km / sec.
In Listing 1 we write an example to test if the particle velocity is less than the speed of light and stop execution if it is false.
Listing 1 : Testing particle velocity without Assert
<pre>package net.javabeat; public class ParticleCalculator { private static final Integer MILE_PER_SECOND = 0; private static final Integer METERS_PER_SECOND = 1; private static final Integer LIGHT_SPEED = 300000; /** * @ Param args @ Throws */ public static void main(String[] args) { // In KM/s Integer particleSpeed = returnParticleSpeed(12, MILE_PER_SECOND); try { if (particleSpeed > LIGHT_SPEED) throw new Exception( "Particle speed can not be greater than the speed of light"); } catch (Exception e) { e.printStackTrace(); } } }
You can see that this code consumes a lot of space just to test a simple proposition. We could simplify this in just one line by using assert.
In Listing 2 below we make the same comparison but using assert hence reducing the complexity of the code. It also facilitates removal of this particular line of code when the application goes to production.
Listing 2 : Using Assert
<pre>package net.javabeat; public class ParticleCalculator { private static final Integer MILE_PER_SECOND = 0; private static final Integer METERS_PER_SECOND = 1; private static final Integer LIGHT_SPEED = 300000; /** * @ Param args @ Throws */ public static void main(String[] args) { // In KM/s Integer particleSpeed = returnParticleSpeed(12, MILE_PER_SECOND); assert (particleSpeed < LIGHT_SPEED): "particle velocity can not be greater than the speed of light" ; } }
If your assert does not work, you must activate it. One way to activate the Eclipse is by following the steps below:
Open Eclipse and go to Window-> Preferences.
Go to Java -> Installed JREs. You must select the JRE you are using and click Edit.
Choosing the JRE
Type “-ea” in the field “Default VM arguments”, which means Enable Assertions.
Enabling Assertions
Figure 2 : Enabling Assertions
After the above configuration, you can run the code paticleCalculator and see the particles assert working. You can even set a value for the particle test assert.
Important Rules on Assertions
Before you start using assert keep in mind a few rules as listed below:
- Do not use Assert so as to replace IF / ELSE. As you have to remove the assert statements when the application goes to production.
- The Assert does not test public methods or values entered directly by the user, ie, variables that are ready to test.
- And the most important: Never make your application depend on the assert, that means the assert should not cause side effects to your application, you should be able to enable and disable it without any problems.
See Listing 3 to understand the wrong usage of the assert.
Listing 3 : Wrong usage of Using Assert
names.remove assert ( null );
This line of code is wrong because you should never link any part of your code to assert. The right way is shown in Listing 4.
Listing 4 : Using Assert correctly
boolean nullsRemoved = names.remove(null); assert nullsRemoved; //Runs whether or not assertions are enabled
Notice in the above code the line “assert nullsRemoved;” ; the code will still work the same way, without any side effects. Just put the assert to make sure that the value is as expected. When the application is put into production, we can comment or remove this line.
Summary
Asserts or assertive is a very powerful feature to increase productivity in the development of systems, so you do not need to get into debugging lines find one simple mistake. If used correctly, will certainly be a strong ally in large projects. If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.