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.
|
|