How To Avoid Null Pointer Exception

NPE or null pointer exception sometimes make programmer feels annoyed. Started to think where the process begin until why it can be happen in the end, will waste time. So before it happen, there are some method that programmer usually do to avoid NPE. Some that I usually do are:

  1. Before do some function, check the parameter first. Will it be null or not? and in the short-circuit logical condition use check null first then other statement. Example:
    public void someExample(String xparam){
    	if(xparam!=null){
    		//do something with xparam
    		return;
    	}
    	
    	/* 
    	another method for checking string, you can use org.apache.commons.lang.StringUtils 
    	*/
    	if(StringUtils.isNotEmpty(xparam)){
    		//do something
    	}
    	
    	/*
    	Another example on short circuit logical
    	*/
    	if( xparam != null && xparam.length() > 2){
    		//do something
    	}
    	
    }
    
  2. When create sort of if condition, make sure the first value never has null value. Example:
    public void someExample(String xparam){
    	String DEFAULT_VALUE = "EMPTY";
    	
    	if(DEFAULT_VALUE.equals(xparam)){
    		//by using this method, if xparam is null,
    		//then result of this if condition will be false
    		//will be NPE if I type it xparam.equals(DEFAULT_VALUE)
    	}
    	
    }
    
  3. Fill the value of variable with default value (no null value please) as much as possible.

Hope there are some another method that you can add for the list above. Happy coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s