Skip to content

Instantly share code, notes, and snippets.

@hamstar
Created August 23, 2011 15:41
Show Gist options
  • Save hamstar/1165493 to your computer and use it in GitHub Desktop.
Save hamstar/1165493 to your computer and use it in GitHub Desktop.
example of drying up code through inheritance, the facade pattern, and convention over configuration
// Get a model from the database, client says
Connection conn = DatabaseConnectionHelper.getConnection(); // make this static
DBFacade db = new DBFacade( conn );
ExampleModel exModel = ExampleModel.find( db, 15 );
exModel.setName('blah').save();
exModel.delete();
// classes
public class SuperModel {
protected DBFacade db;
protected Map row;
public SuperModel( DBFacade db, int id ) {
this.db = db;
}
/**
* Get the name of the table by figuring out the name of this model
* and using that as the table name (minus Model)
* ( you could also store a constant in the child table called TABLE_NAME )
*/
final public String getTable() {
String[] strings = this.getClass().getName().split("\\."); // split the package/class
String className = strings[1];
// Build the table name
return className.substring(0, className.length()-5).toLowerCase();
}
private void populateModel( int id ) {
Map where = new Map<String, String>();
where.put( 'id', id.toString() );
row = this.db.where( where ).get( this.getTable() );
}
public void delete() {
Map where = new Map;
where.put( 'id', this.row.get('id') );
this.db.where( where ).delete( this.getTable() );
}
public void save() {
// need to detect if this is an insert or an update
}
/**
* Act as a mini factory in static context
*/
}
public class ExampleModel extends SuperModel {
public ExampleModel( DBFacade db, int id ) {
super( db, id );
}
public static ExampleModel find( DBFacade db, int id ) {
return new ExampleModel( db, id );
}
public String getName() {
return this.row.get('name');
}
}
public class DBFacade {
private Connection conn;
public int lastInsertId() {
}
public ArrayList getColumnList() {
}
public DBFacade where() {
return this;
}
public DBFacade select() {
return this;
}
public Map get( String table ) throws SQLException {
}
public DBFacade insert( Map data, String table ) throws SQLException {
return this;
}
public DBFacade update( Map data, String table ) throws SQLException {
return this;
}
public DBFacade delete( String table ) throws SQLException {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment