File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes when to use assertions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "when to use assertions" Watch "when to use assertions" New topic
Author

when to use assertions

jon ruane
Greenhorn

Joined: Mar 08, 2007
Posts: 13
ok, what i've learnt (from studying Kathy and Berts SCJP study guide for java 5), is that one of the places you shouldnt use assertions is in public methods.

this makes sense as your public methods are the 'way-in' to your application from the outside world, and thus must have some kind of protection that guarantees certain contraints on the arguments of the public methods will be inforced.

as assertions arent guaranteed to be enabled, this enforcement might not happen. so dont rely on them.

my questions is: based on the above, why are we then advised to use assertions, even in public methods, to check for cases that you know are never ever supposed to happen?

for example a case statement:

switch(x) {
case 2: ......
case 3: ......
case 4: ......
default: assert false;
}

in the above, we are assuming that x will be either 2,3 or 4. anything else and we want to alert the user of a problem via an assertion.

following on from my 1st point, if assertions are disabled then in the above case statement a value other than 2,3 or 4 will slip through the net, and we will be unaware of this.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3446
    
  12
IMO, assertions should only be used during development. They are intended to warn the developer that a situation that the design says should never happen has happened and that the code needs to be modified to stop it happening. They should not be used as validation in production code except for debugging purposes.


Joanne
Eric Daly
Ranch Hand

Joined: Jul 11, 2006
Posts: 143
Hi jon, I don't know if I will answer your question, but I think this may help. I have been reading this page and it talks about using assertions in java.
One thing I noticed was actually in the first paragraph... assertions are used for debugging purposes. You use an assertion to make darn sure that anything you assume to be true in your code is actually true. Plus the earlier you catch a bug, the better.
Any other input would be great, and correct me if I'm mistaken.


Studying for SCJP 6
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38334
    
  23
They mention the Eiffel language on the web page you mentioned. The Eiffel people (cf Meyer B, Object-Oriented Software Construction 2/e Upper Saddle River NJ: Prentice-Hall (1998), page 333ff) use the concept of Design-by-Contract (TM), which builds on early work by C A R Hoare.

A function/procedure/subroutine/method is considered correct if the following applies:-

  • It is considered to consist of three parts, {P} A {Q}.
  • P is the precondition, Q is the postcondition, and A is the actual coding.
  • P has to be true before the processing starts.
  • The coding then must ensure and guarantee that Q will be true after the coding starts.
  • There is also an invariant, which must be true before and after every method (but maybe not during methods)

  • Example of preconditions: when depositing money in the bank, the amount recorded is greater than zero.
    Example of postconditions: when depositing money, the total in the account has increased by the amount of deposit.
    Example of invariant: in a circle the area is PI*r^2 within the bounds of precision available from the arithmetic.

    You use the precondition assertion principally to check that the parameters passed are correct, and the postcondition assertion to check that the method is working as expected. You will find precondition assertions passim in the API docs; look at the three-argument constructor for java.awt.Color, and you find it has a precondition assertion in. It might not look like an assertion, but it is printed as:-
    Throws:
    IllegalArgumentException - if are, g or b are outside of the range 0.0 to 1.0, inclusive.
    As Eric Daly says
    You use an assertion to make darn sure that anything you assume to be true in your code is actually true.
    Then, as Joanne Neal implies, once you are happy it is working and you can let the code loose on an unsuspecting world, you disable all the assertions.


    I know most people think "are" is not short for red the way g and b are short for green and blue, but the website computer thinks I am using the letter one after Q as a prohibited abbreviation.
    Eric Daly
    Ranch Hand

    Joined: Jul 11, 2006
    Posts: 143
    Campbell Ritchie, I don't know if it's just me, but your very last sentence made absolutely no sense at all. Maybe I'm tired, or maybe there's a typo... I don't know. But it's unintelligible to me. No offense, I'm actually curious as to what you meant. Just really, really confused.
    jon ruane
    Greenhorn

    Joined: Mar 08, 2007
    Posts: 13
    Thanks for all the useful advice.

    why i have questioned the information in the SCJP book, is that i have seen questions in mock exams that ask: where/when should you not use assertions, and my answers have been the 3 places im told:

    1. in public methods
    2. the validate command line arguments
    3. anywhere that can cause a side effects

    then i see that there is a twist to the public method rule. i dont like uncertainty, and if im asked the above question in an exam, then i'll will be hesitating in my answer.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 38334
        
      23
    I put in the three letters which begin red green blue, but the computer won't let me post rgb as three separate letters. Even though I quoted a snippet from the Color class API.
    It gives an error saying that the first letter of red is short for "are" and it is a stupid abbreviation only used in texting. So you end up with me writing "are g b" instead of rgb. Does that help??? Try posting something with rgb as separate letters. That is why I was saying things incomprehensible.

    Sorry
    Eric Daly
    Ranch Hand

    Joined: Jul 11, 2006
    Posts: 143
    Haha, I understand now. That's stupid. It's areeally areediculous.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 38334
        
      23
    Pleased to sort out the misunderstanding.

    The point I was making was that the Color class constructors have a precondition which is enforced by throwing an Exception.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: when to use assertions