Previous
Index

Next

Objective 5 and 6 Using Assertions

Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions Identify correct statements about the assertion mechanism.

Comment on the objective

Assertions were added to the objectives for the Sun Certified Java Programmers Exam with the release of the version of the exam for JDK1.4 released in the middle of 2002. As they are a new feature of the exam you can be very confident of getting such questions on the exam. Assertions are a feature of other Object Orientated languages and there has been pressure for a while for them to be added to Java.

Assertions were added to the Java language with the release of JDK1.4 so there is not a significant body of writing on the topic at the time of writing.

Why Assertions exist

Assertions are available in C++ but not in C or Visual Basic (or Pascal to my knowledge) so there are many people who have not used them. If it comes to that there are plenty of C++ programmers who have not used them. Assertions are a fairly simple concept where you write a statement that should always be true, but in a form that can be removed from the finally compiled version of the code so they cause no runtime overhead. It would be perfectly possible to write code using the constructs available in Java prior to JDK1.4 that simulates the functionality of assertions but it would be hard to do so in such a way that they would be turned off at runtime.

In the C/C++ languages assertions can be created using language pre-processor and there have been huge amounts of discussions in newsgroups as to if the Java language should have a pre-processor system. Opinions divide between those who consider pre-processor macros to be the work of the devil that gives opportunities for the creation of overly complex constructs and those who consider it an incredibly powerful addition to a language. Either way the Java designers declined to implement a pre-processor facility and JDK1.4 includes assertions.

How assertions are used

Where and how you use assertions is a matter of judgment in a similar way to where and how you use comments. Some programmers rarely comments and this style of programming is widely known as poor programming. Because around 80% of coding is maintenance by people other than those who wrote the original comments are very important. Assertions can be considered an extension of comments in that comments are often used to tell a person reading the code that a particular statement or piece of code should always be true. With assertions, instead of indicating by a comment that a statement should always be true you can assert that it should always be true.

If you then run the code with assertions enables you do not have to rely on a close reading of the code as you would with comments but the running of the code itself will check your assertions are true, and if they are not an assert error will be thrown.



By default, assert statements are disabled during normal program run.



As the name implies assertions are used to assert something that should always be true. When a program is running normally assertions are disabled and cause no performance overhead. When a programmer is investigating an issue assertions can be enabled and if any of the assert statements are not true an assert exception will be thrown. Assertions are a key part of JDK 1.4 and require no additional import statements in the source code. However because programmers in the past have used the word assert in creating their own versions of assertions the compilation process requires a command line parameter to tell it that it will be using the genuine JDK 1.4 version of assertions. This takes the form

javac -source1.4 Myprog.java

If you then run the program normally in the form

Java Myprog

assertions are disabled and no assert exceptions will be thrown. If you subsequently have an issue you want to investigate and confirm that all of the assertions of items that should always be true, really are true you can run the program with assertions enabled as follows.

Java -enableassertions Myprog

What should you assert to be true?

Assertions should be used for anything you believe should always be true. For example it should always be true that a person has an age greater than zero. If a person has an age less than zero your program or its input has a significant problem. For another example if you were recording the date of a persons death you program (or your morality) might have a problem if you had the date of death in the future, therefore you could assert that the date of death is in the future.

For example if you are falling through a case statement or a set of if/else statements you might believe that the code should always exit before it reaches the final test. Imagine if you had an application dealing with media types. Your application might be expecting to deal with jpg,mpg,avi or gif files. You set up a case statement that branches according to the type of file. Because you believe that the type will always be one of those file types there is definitely a problem if you get to the end of the case statement without branching and you can place an assert statement at the location of the default option.

Where should you use assertions?

Assertions should not be used to enforce the public interface of a program. One of the most public interfaces of a program is its command line parameters. Thus traditionally a programmer will inspect the command line passed to a Java program by looking at the value in the String args array passed from the command line. Typically if this array does not contain the expected type of values the program will exit and print a message indicating what the correct format of the command line should be. The introduction of the assert mechanism does not change this. It is not appropriate to use assert to check the command line parameters of a program because assertions will not always be enabled.

It is not appropriate to use assertions to check the parameters passed to public methods. Because your public methods may be used in programs written by other people you cannot be certain that they will have assertions enabled and thus the normal running of the program may be faulty. However it is appropriate to use assertions for checking the parameters to private methods as these will generally only be called by code written by people who have access to the source of those methods. The same assumption may be made for code in protected or in package protected methods. As you can see these are only general guidelines but the exam may ask questions based on these type of guidelines.

Assert syntax

The assert statement has two formats

The simple

assert somebooleatest

and

assert somebooleantest : someinformatinvemethod

In the first simpler version the assert tests that something is true and if it is not an assert error is thrown. For example if you were testing that a persons age was greater than zero you might create an assert in the form

assert (iAge>);

The more complex version might be of the form

assert (iAge) :"age must be greater than zero";

This example is simple in that the right hand side of the expression is a simple string, but this could be any method call that returns a value, ie a method with any return type except void.

Questions

Question 1)

Which of the following statements are true?

1) Using assertions requires importing the java.util.assert package
2) Assertions should be used to check the parameters of public methods
3) Assertions can be used as a substitute for the switch/case construct
4) An assertion that a persons date of death > date of birth is appropriate

Question 2)

If the following code is successfully compiled and run without explicitly enabling assertions, what will happen?

class Language{
    public static final int java=1;
    public static final int pascal=2;
    public static final int csharp=3;

}
public class Mgos  {
    static int lang=0;
    public static void main(String argv[]){
        switch(lang){
        case Language.java:
            System.out.println("java");
            break;
        case Language.pascal:
            System.out.println("pascal");
            break;
        case Language.csharp:
            System.out.println("csharp");
            break;
        default:
            assert false : lang;
        }

    }

}

1) An unmatched parameter exception will be thrown
2) An assert exception will be thrown
3) The program will run with no output
4) Output of "csharp"

Question 3)

Which of the following are good candidates for using the assert construct?

1) An input form has a field for a persons age. If the person entering the date of birth and the date of death enters an age of death that is before the age of birth the assertion mechanism is used to cause a dialog warning box to be shown and the data will not enter the system.

2) A Text Editing program has a file save mechanism. The assert mechanism is used to check if the drive that is being save to really exists. If the drive does not exist an assertion will be thrown generating a warning to the program operator.

3) A program is being created for food preparation that involves cooking meat. Code is included so that if the value of a temperature variable reading appears to be negative an assert exception is thrown.

4) A school attendance system is being created. In the system is code that will throw an assert exception if a childs age is calculated to be less than zero.

Question 4)

What will happen if you attempt to compile following code with JDK1.4 with assertions enabled 

public class Bbridge{
    int iRunningTotal=0;
    public static void main(String argv[]){
        Bbridge bb = new Bbridge();
        bb.go(argv[0]);
    }   
    public void go(String s){
        int i = Integer.parseInt(s);
        setRunningTotal(i);             
        assert (iRunningTotal > 0): getRunningTotal();
    }
    public String getRunningTotal(){
        return "Value of iRunningTotal "+iRunningTotal;
    }
    public int setRunningTotal(int i){
        iRunningTotal+=i;
        return iRunningTotal;
    }
}

1) Compile time error, getRunningTotal does not return a boolean
2) Compile time error malformed assert statement
3) Compilation and no output given a command parameter of 1
4) Compilation and assert error given a command parameter of 0

Question 5

Which of the following statements are true?

1) The assert system introduces no backward compatibility issues
2) The assert system should be used to enforce command line usage
3) Asserts should be used to check for conditions that should never happen
4) Asserts can be used to enforce argument constraints on private methods.

Answers

Answer to Question 1)

4) An assertion that a persons date of death > date of birth is appropriate

The use of assertions does not require the import of any packages, however it does require JDK1.4 or better and the use of command line parameters to the JDK tools. Assertions should not be use to check the value of method parameters as during normal (non test) mode assertion checking will be disabled. The concept that the date of a persons death will be greater than the date of a persons birth should always be true and is thus an appropriate use of the assert construct.

Answer to Question 2)

3) The program will run with no output

Without explicitly enabling assertions from the command line when the program is run no assertion error will be produced

Answer to Question 3)

3) A program is being created for food preparation that involves cooking meat. Code is included so that if the value of a temperature variable reading appears to be negative an assert exception is thrown.

4) A school attendance system is being created. In the system is code that will throw an assert exception if a childs age is calculated to be less than zero.

The crucial difference between options 1 and 2 and 2 and 4 is that in options 1 and 2 the assert mechanism is required during the normal run of the program. The assert mechansim should not be required for the normal running of a program or for standard runtime checking. Of course for options 3 and 4 you might want to include runtime checking instead of assertions, but because the description does not indicate that the outcome of a normal run of the program depends on this test using assertions might be appropriate.

Answer to Question 4)

3) Compilation and no output given a command parameter of 1
4) Compilation and assert error given a command parameter of 0

Answer to Question 5

3) Asserts should be used to check for conditions that should never happen
4) Asserts can be used to enforce argument constraints on private methods

A minimum knowledge of the way programming languages works might indicate that a new feature is like to cause some backwards compatibility issues. If a programmer has used the word assert as a variable with a JDK prior to 1.4 you will need to pass a command line parameter when using JDK1.4 to indicate this. It is not appropriate to check the command line parameters using assertions because assertion checking will not always be turned on.


Other Resources on this topic

The Sun tutorial
http://java.sun.com/j2se/1.4/docs/guide/lang/assert.html

The Java Developer Connection (JDC)
http://developer.java.sun.com/developer/JDCTechTips/2002/tt0409.html

From the JavaRanchNewsletter
http://www.javaranch.com/newsletter/Sept2002/newslettersept2002.jsp#whim

Khalid and Mughal
http://www.ii.uib.no/~khalid/pgjc/jcbook/JC2_Ch05-assertions.pdf



Previous
Index

Next