Beyond Java Buzz

home

You cannot pass code blocks in Java

below is an example of a Dao pattern implementation

  • you would really like to have the open/close connection code in one spot in your app
  • you would really like to pass in variable code to the routine
  • since you can't easily do this in Java, most apps tend to copy and paste the connection closing code, which leads to bugs (ie, connections left open...)
  • Note: you can't easily do this in Java, but it can (and should...) be done.
  • In a typical Dao pattern implementation, you would like to vary the contents of the while loop. What exists around the while loop(opening and closing connections...) should be constant.
    private Result getResultsetData(String sql) {
        Connection conn = null;
        ResultSet rs = null;
        int colCount = 0;
        int[] colWidths = null;
        long rowCount = 0;
        String[] colHeaders;
        Result result;  
        
    	
        try {
            conn = this.getConnection();
            rs = conn.prepareStatement(sql).executeQuery();
            colCount = rs.getMetaData().getColumnCount();
            result = new Result(colCount);
    
            while (rs.next()) {
                //append to buffer
                for (int i = 1; i < colCount + 1; i++) {
                    result.add(rs.getString(i));
    
                }
    
            }
            return result;
    
        } catch (Exception e) {
        	return new Result( e.getMessage());
        } finally {
            try {
                rs.close();
            } catch (Exception ee) {     }
            try {
                conn.close();
            } catch (Exception ee) {    }
    
            
        }
        
    }