Results 1 to 3 of 3

Thread: Proper way to handle null values?

  1. #1
    Join Date
    Jul 2006
    Posts
    5

    Default 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. #2
    Join Date
    Mar 2006
    Location
    A place to call home
    Posts
    76

    Default

    Some good old Spring AOP maybe?

  3. #3
    Join Date
    Jul 2006
    Location
    Kolkata, India
    Posts
    217

    Default

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •