-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: [slightly OT] How to avoid NullPointerException
PostPosted: Wed Feb 02, 2005 2:31 pm 
Newbie

Joined: Mon Sep 06, 2004 1:39 pm
Posts: 18
Location: Utah, USA
I am developing an application using Hibernate and I find myself doing some goofy things to get around NullPointerExceptions. Let's say that I have a business object Order which is composed as follows:

public class Order {

private String name;
private Address address;
private String phone;

// default constructor
public void Order () {
}

/* implement basic getters/setters */
}

From the standpoint of business logic only 'name' and 'address' are required, 'phone' is not. At some point in my application I need to print an order invoice. I request the object from Hibernate through my DAO which is working fine. Occasionally I'll receive back an Order object for a record that contained no 'phone' value and so the member attribute 'phone' does not point to a String object, but rather to null. When I try to print this I get the NullPointerException.

I can think of a couple of ways to get around this, but I'm not sure they're the best solutions.

First method: change the declaration in my class to 'private String phone = "";'. This way when a new object is created everything is guaranteed to point to an object. With this solution I'm worried about performace penalties (keep in mind that my objects are quite a bit more complicated than what is shown here).

Second method: build a member method 'conditionNulls () ' that can be called right before I try to print the object. This method would verify that each member attribute contained a reference to an object, not null. In some cases it would have to initialize it (e.g. 'if (this.phone == null) this.phone = ""').

I suspect that there is some more appropriate way to accomplish what I am aiming for. All comments welcome.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.