Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assertion question

 
Raj Puri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have:
assert(i>5);
j = 10;
Now I put the code in production disabling assertion. How will the application get affected if infact there was a bug in my assumption that i > 5 . This could have bad affects on programs. How does Java handle this? I guess Java does not care, onus of asserting is yours?
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rajesh
Assertions are a mechanism for the tester/progammer/anyone concerned to check that the code is fine during testing. In case later you find a bug you can simply enable assertions and check if there is really a problem with your assumption.
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would have thought it quite valuable to enable assertions for production. The extra runtime cost is small or zero - remember, AssertionError will only be thrown if the program does something like break an internal invariant.
 
Raj Puri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To have assertion disabled is a big risk, considering that there is no way one can be 100% sure that what you assert is really always true or there is no program error. Seems once assertion is used in development and disabled there is no place to go except to see system getting broken!!
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not agree with having exceptions always enabled.
The main situations in which assertions are not appropiate are related the fact that they might not be enabled.
If assertions were intended to be always on, they are useless; we could use exceptions or print statements. I think their advantage is that they can be used while developing/testing, and, in case of problems on production time can be enabled as well.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic