Announcement Announcement Module
Collapse
No announcement yet.
Proper way to handle null values? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Proper way to handle null values?

    Hello,

    As it bothers me checking null values repeatedly I've been wondering if Spring provides anything to deal with them. So far I've been using following class.

    Code:
    public class RowWrapper {
    
    	private ResultSet resultSet;
    
    	public RowWrapper(ResultSet resultSet) {
    		if (resultSet == null) {
    			throw new IllegalArgumentException("resultSet == null");
    		}
    
    		this.resultSet = resultSet;
    	}
    
    	public synchronized String getString(String columnLabel) throws SQLException {
    		return checkNullValue(resultSet.getString(columnLabel));
    	}
    
    	public synchronized Double getDouble(String columnLabel) throws SQLException {
    		return checkNullValue(resultSet.getDouble(columnLabel));
    	}
    
    	public synchronized Integer getInt(String columnLabel) throws SQLException {
    		return checkNullValue(resultSet.getInt(columnLabel));
    	}
    
    	// ...
    
    	private <T> T checkNullValue(T value) throws SQLException {
    		if (resultSet.wasNull()) {
    			return null;
    		}
    
    		return value;
    	}
    }
    greets
    Bernhard Huemer

    EDIT: I guess I've misplaced this thread, sorry.

  • #2
    Some good old Spring AOP maybe?

    Comment


    • #3
      To address your concerns at a slightly broader perspective ..

      a) Handling null validations like u have done in ur code snippet as :

      Code:
          if (resultSet == null) {
                  throw new IllegalArgumentException("resultSet == null");
          }
      Jakarta Commons offer a nifty class org.apache.commons.lang.Validate, which helps you do so.

      b) Handling null checks repeatedly can be done using the helper class that u have already written OR as suggested you can use AOP to weave this functionality.

      c) For handling cases where you would like to have a uniform interfaces for handling null objects, think about using the Null Object pattern. This offers a nice way of handling nulls seamlessly and make your code look much better.

      HTH.
      - Debasish

      Comment

      Working...
      X