So working through a few Java based web applications, I realized one common thing in pretty much most of the web applications. Most of them tend to run fine until you meet face to face with a Null Pointer Exception.
Below is one of the methods that is returning an error:
public Map getWebSiteObjects(String path, LightWeightNode root, Integer versionId, Site site) {
Map webSiteObjects = new HashMap();
// refresh site
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
Scenario: This method generates a tree on my application, however, it's giving a null pointer exception at runtime:
2014-10-09 12:00:18,674 ERROR org.springframework.web.servlet.DispatcherServlet - Could not complete request
java.lang.NullPointerException at com.bsdeurope.xmlcms.service.impl.TreeManagerImpl.getWebSiteObjects(TreeManagerImpl.java:159)
Now I'm quite new with some Java principals(fundamentals) and my idea to solve this was to initialize the 4 variables passed in the method therefore have:
path = null;
root =null;
versionId = null;
site = null;
before any instructions within the getWebSiteObjects
method. Now I know this might not be the only solution but my question is:
1) What is good practice in terms of preventing Java Null Pointer Exceptions
?
2) If there is a procedure how would you go about doing it?
Usually when working with a lot of classes especially applications with code that is badly written you end up hitting your head against the wall when you get tons of null pointer exceptions left, right and center.