When to Use the Safe Dereferencing ?. Operator in Groovy

  • google plus

In Brief...

The NullPointerException is the bane of Groovy (and Java) developers! What if an operator existed that might mitigate the occurrences of this dreaded exception? An operator does exist in Groovy to help us out: the safe dereferencing operator, ?.. In this topic you will find out when to use this operator.

Instructions

To learn when to use the safe dereferencing operator in Groovy follow these 6 steps:

  1. Open your text editor and type in the following lines of Groovy code:
    
    def fullName
     // The following line will cause a NullPointerException
    println "Display length of  fullName: ${fullName.length()}"
    
    You can probably see the problem right off the bat: the string variable has not been initialized! Of course, this is a very simple program but in the real world programs are much more complicated and you might not be aware that a certain string (or an object in general) is initialized . We will go ahead then and run this program to witness the exception first hand.
  2. Save your file as SafeDereferencing.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run safe dereferencing with error script
    The output displays a NullPointerException because we are attempting to use a property (length) on a string that was never initialized.
  4. Return to your editing session and change fullName. to fullName?. on the println statement as shown below:
    
    def fullName
     // The following line will cause a NullPointerException
    println "Display length of  fullName: ${fullName?.length()}"
    
    You can remove the comment too because now the program will not terminate with a NullPointerException. In general, use the safe dereferencing operator any time you are attempting to access a method of an object unless you are certain the object has been initialized!
  5. Save your changes.
  6. In the command prompt, type in the command to interpret and run your script:
    Run safe dereferencing script
    The output displays the value of the length as null and this verifies that a NullPointerException was NOT thrown because of the safe dereferencing operator.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss