Header Ads

Do's and Don'ts While Working With Assertions In Java

In my last post (http://www.mydigitalvoice.in/2013/05/assertion-concept-simplified-in-java.html). I have briefed how to work with assertion. Now in this post let us check out few rules and best practices to work with assertion.



Let us follow few common rules:


Do not mix business logic/programming logic with Assertion. As assertion will not run always until assertion is enabled.(Please refer here for more)

Good coding practice:
amount_withdraw(int amount)
{
//some validation
if((amount<100 || amount>=5000))
System.out.print("This amount can not be deducted");
else
//let user deduct the amount
}
Bad coding practice:
amount_withdraw(int amount)
{
//some validation
assert(amount>=100)||assert(amount<5000)
//let the user allow to get data
}

During debugging,in our program, the best place to put assertion where control does not reach or not allowed to reach.(Please refer here for more)
Good coding practice:
switch(month_val)
{
case 1: System.out.println("Jan");break;
case 2: System.out.println("Feb");break;
case 3: System.out.println("Mar");break;
......
......
case 12: System.out.println("Dec");break;
default: assert(false);
}
This is not violating 1st rule ..if the month value is anything other than 1 to 12.We need to check. Hence it is valid.

  • It is a bad practice to use assertion inside public method.As the public methods will be accessed by outside coders and method consumers, they will not be knowing whether to enable or disable assertion.
  • Secondly it is always good to have assert for private method as the method designer is local and can check the assertion
  • Thirdly, this not good to put assert while validating command line argument. This can be argument of public main method.(Please refer here for more)
Let us check with some example.
class assertTest{
public static void main(String... args)
{
asset(args.length<5):"Need more inputs";

}
}


  • All the assertion errors are child class of Error. Super class Error is unchecked during compile time hence assertion error will be unchecked.
  • All the assertion errors will be raised when the assertion will fail during run time
  •  It is legal to catch assertion error but the objective of assertion is to fail if something is not as per programmer's expectation.So it is not recommended to use.(Please refer here for more)
class assertTest{
public static void main(string... args)
{

int a=12;
-----
-----
-----
try
{
assert(a>12);
}
catch(AssertionError e)
{
//some code
}
}
}

Powered by Blogger.