java Code: Simple, Clean, Reusable

Whereas Web-based m - v- c applications and other layered systems tend to use very different programming models between layers, within layers the function for one data object tends to resemble closely the function for a different data object.  This is particularly true for applications that rely heavily on CRUDS methods to provide their core functionality.

For example, the way one builds the components for the Control layer is very different from the way one builds the components for the Domain Model layer.  However, the way one builds the Domain Model layer for, say, a Customer object is likely to closely resemble the way one builds the Domain Model for a Product object, at least with respect to CRUDS methods.

Realizing this, one can design and implement code for one data object and then use that code as a pattern for other data objects --  that is, if one has built the code so that it is clean, modular, and as consistent as possible in the way it implements similar function.

The samples below attempt to give an idea of code that can be generalized to other similar methods as well as to other data objects.


Struts Action

public class ActionUserAdmin extends Action {

	public ActionForward execute(
			ActionMapping mapping, 
			ActionForm form,
			HttpServletRequest request, 
			HttpServletResponse response)
			throws Exception {
		
		// return value
		ActionForward forward = new ActionForward(); 

		//  get session state
		HttpSession session = request.getSession();	
		
		// FormBean version of input and return values		
		FormBeanUser formBean = (FormBeanUser) form;  
		FormBeanUser formBeanNew;

		//  DataBean version of input and return values
		BeanUser dataBean = mapFormBeanToDataBean( formBean ); 
		BeanUser dataBeanNew;

		//  get admin user's specific role
		String role = (String) session.getAttribute("role");

		// instantiate model
		ModelUserAdmin model = new ModelUserAdmin(); 

		// get userAction requested and trim
		String userAction = ( (String)(request.getParameter("userAction")) ).trim(); 
				
//		handle userActions
		
		//  cruds actions
		
		if ( (userAction.equalsIgnoreCase("add")) )  {
			
			//  call model
			dataBeanNew = model.add( dataBean, role );
	
			//  test failure
			if ( !(dataBeanNew.isOk()) )  {
					
				formBean.setMessage( "Error in add." );
				request.setAttribute( "formBeanUser", formBean );
				forward = mapping.findForward("failure");
								
			//  test success
			}  else  {
				
				formBeanNew = mapDataBeanToFormBean( dataBeanNew );
				
				formBean = formBeanNew;
				formBean.setMessage( "add OK." );
				request.setAttribute( "formBeanUser", formBean );
				forward = mapping.findForward("success");
			
			}		
			
		} else if ((userAction.equalsIgnoreCase("delete")) )  {
			.
			.	
			.

		}
		
		return forward;
	}

	public static BeanUser mapFormBeanToDataBean ( FormBeanUser fb )  {
		
		BeanUser tb = new BeanUser();
		
		tb.setUserId    	( fb.getUserId() );
		
		tb.setNameFirst   	( fb.getNameFirst() );
		tb.setNameMiddle  	( fb.getNameMiddle() );
		tb.setNameLast    	( fb.getNameLast() );
		
		tb.setAddress1    	( fb.getAddress1() );
		tb.setAddress2    	( fb.getAddress2() );
		tb.setCity        	( fb.getCity() );
		tb.setState       	( fb.getState() );
		tb.setPostalCode   	( fb.getPostalCode() );
		tb.setCountry   	( fb.getCountry() );
		
		tb.setPhone   		( fb.getPhone() );
		tb.setFax    		( fb.getFax() );
		
		tb.setEmail       	( fb.getEmail() );
		tb.setPassword      	( fb.getPassword() );

		tb.setRole      	( fb.getRole() );

		tb.setCollectionBeanId	( fb.getCollectionBeanId());
		
		return tb;
		
	}
	.
	.
	.
	
}
 

Model

public class ModelUser implements IModelUser {
	
//	cruds methods
	
	public BeanUser add( BeanUser dataBean )  {
		
		//  test email does not exist
		if ( emailExists(dataBean) )  {
			dataBean.setOk( false );
			return dataBean;
		}

		// generate and add key
		dataBean.setUserId( Util.getUniqueID() );
		
		//  create sql resources
		Statement statement = null;
		Connection connection = null;
		
		// open database
		connection = openDataBase();
		if ( connection == null )  {
			System.out.println("ModelUser.add: null Connection" );			
			dataBean.setOk(false);
			return dataBean;		
		}
		
		// create sql
		String query = createInsert( dataBean );
		if ( query == null )  {
			System.out.println("ModelUser.add: null createInsert" );			
			dataBean.setOk(false);
			return dataBean;		
		}

		// add to database
		try {
			statement = connection.createStatement();
			int result = statement.executeUpdate( query );
			
			//  test failure
			if ( result == 0 )  {
				System.out.println("ModelUser.add: null ResultSet" );			
				dataBean.setOk(false);		
			//  test success
			}  else  {
				dataBean.setOk(true);		
			}
				
		} catch (SQLException e) {
			System.out.println("ModelUser.add.SQLException: " + e.toString() );			
			dataBean.setOk(false);
			
		}  finally  {
			
			try {				
				statement.close();
				connection.close();
				
			} catch (SQLException e) {
				System.out.println("ModelUser.add close resourses error: " + e.toString() );			
				e.printStackTrace();
				dataBean.setOk(false);
			}
			
		}
										
		// return DataBean 
		return dataBean;
				
	}	
	.
	.
	.

	// utility Methods 
	
	private Connection openDataBase() {
		
		String driver 	= Context.getMySQLDriver();
		String url 	= Context.getMySQLUrl();
		String userName = Context.getMySQLUserName();
		String password = Context.getMySQLPassword();

		try {
			
			Class.forName  (driver);
			Connection con = DriverManager.getConnection ( url, userName, password );
			return con;
			
		} catch (ClassNotFoundException e) {
		
			System.out.println("ModelUser.openDataBase.ClassNotFoundException: " + e.toString() );			
			return null;
	
		} catch (SQLException e) {
			
			System.out.println("ModelUser.openDataBase.SQLException: " + e.toString() );			
			return null;

		}  
		
	}
	
	private String createInsert( BeanUser dataBean ) {
				
		//INSERT INTO Person ( NameFirst, NameLast, City ) 
		//VALUES ( "john", "smith", "carrboro" );
		
		
		String 	sqlString  = "INSERT INTO User ( userId, nameFirst, nameMiddle, nameLast, address1, address2, city, state, postalCode, country, phone, fax, email, password, role ) ";
				sqlString += "VALUES ( ";
				sqlString += "'" + dataBean.getUserId() 	+ "', ";
				sqlString += "'" + dataBean.getNameFirst() 	+ "', ";
				sqlString += "'" + dataBean.getNameMiddle()	+ "', ";
				sqlString += "'" + dataBean.getNameLast() 	+ "', ";
				sqlString += "'" + dataBean.getAddress1() 	+ "', ";
				sqlString += "'" + dataBean.getAddress2() 	+ "', ";
				sqlString += "'" + dataBean.getCity()		+ "', ";
				sqlString += "'" + dataBean.getState() 		+ "', ";
				sqlString += "'" + dataBean.getPostalCode() 	+ "', ";
				sqlString += "'" + dataBean.getCountry() 	+ "', ";
				sqlString += "'" + dataBean.getPhone()		+ "', ";
				sqlString += "'" + dataBean.getFax() 		+ "', ";
				sqlString += "'" + dataBean.getEmail() 		+ "', ";
				sqlString += "'" + dataBean.getPassword() 	+ "', ";
				sqlString += "'" + dataBean.getRole() 		+ "'";
				sqlString += " )";
							
		return sqlString;		
	
	}
	

SuperClass

public abstract class GESModelUIJDBC implements IGESModelUI {


// **********  Interface Methods  **********


	public GESDataBean add( 
		GESDataBean dataBean 
		) {

		//  create unique id for databean to be used as dbms key
		//dataBean.setId( GESUtils.getUniqueId() );   //  changed by jbs, 10,07
		
		//  create sql resources
		Statement statement = null;
		Connection connection = null;

		try {
			
			//  get connection to dbms
			connection = getConnection( );
		
			// create & populate sql statement string
			String query = createInsertString( dataBean );
			if ( query == null )  {
				return null;		
			}

			//  create and execute jdbc statement
			statement = connection.createStatement();
			int result = statement.executeUpdate( query );
			
			//  verify results
			if ( result == 0 )  {
	 			System.out.println( "Error in " + getClassName() + ".add: error sending data to DB." );
				return null;	 		
			}  /*else  {
				dataBean.setMessage("DataBase Add successful");			
			}*/
 			 		
		} catch (SQLException e) {
			
			System.out.println( "Error in " + getClassName() + ".add: " + e.getMessage() );
			return null;		
			
		} catch (GESException e) {  	
			
			System.out.println( "Error in " + getClassName() + ".add: " + e.getMessage() );
			return null;
			
		}  finally  {  // end catch		
		
			//  close sql statement and connection
			try  {			
				if ( statement != null ) statement.close();
				if ( connection != null ) connection.close();			
			}  catch ( SQLException e )  {  // end try			
				System.out.println( "Error in " + getClassName() + ".add: " + e.getMessage() );		
			} 	
		
		}  // end finally

		return dataBean;
		
	}
	
	.
	.
	.

  	//  **********  Abstract Methods  **********
  		
	protected abstract String getClassName();

	protected abstract GESDataBean getReturnBean();
	
	protected abstract Connection getConnection()
 		throws GESException;  
	
	protected abstract String getKey( GESDataBean dataBean );
	
	protected abstract String createInsertString( GESDataBean dataBean );
	
	protected abstract String createDeleteString( GESDataBean dataBean );
	
	protected abstract String createUpdateString( GESDataBean dataBean );
	
	protected abstract String createFindString( GESDataBean dataBean );
	
	protected abstract String createSearchString( GESDataBean dataBean );

	protected abstract Collection mapRSToBeans( ResultSet resultSet );
	
	protected abstract GESCollectionBean buildCollectionBean( Collection dataBeans );

	
}