Skip to content

Instantly share code, notes, and snippets.

@stijnvanbael
Last active December 17, 2015 15:59
Show Gist options
  • Save stijnvanbael/5635429 to your computer and use it in GitHub Desktop.
Save stijnvanbael/5635429 to your computer and use it in GitHub Desktop.
Example on how to guide the API user with a method chain and a class implementing multiple interfaces
public class GuidedMethodChainExample {
public static void main(String[] args) throws SQLException {
// The method chain should read like natural language
ResultSet rs = SQLQuery.selectFrom("employee")
.where("first_name").isEqualTo("John")
.and("last_name").isEqualTo("Doe")
.execute();
}
// These interfaces limit the scope in the method chain
public interface SQLQuerySelect {
SQLQueryCondition where(String columnName);
}
public interface SQLQueryWhere {
SQLQueryCondition and(String columnName);
ResultSet execute() throws SQLException;
}
public interface SQLQueryCondition {
SQLQueryWhere isEqualTo(String value);
}
// Implements multiple interfaces so it can pose as any scope
public final class SQLQuery
implements SQLQuerySelect, SQLQueryCondition, SQLQueryWhere {
private StringBuilder sql;
private List<String> values = new ArrayList<String>();
private SQLQuery(String tableName) {
this.sql = new StringBuilder("SELECT * FROM ").append(tableName);
}
public static SQLQuerySelect selectFrom(String tableName) {
return new SQLQuery(tableName);
}
// Return the interface for the desired scope
@Override
public SQLQueryCondition where(String columnName) {
sql.append(" WHERE ").append(columnName);
return this;
}
@Override
public SQLQueryWhere isEqualTo(String value) {
sql.append(" = ?");
values.add(value);
return this;
}
@Override
public SQLQueryCondition and(String columnName) {
sql.append(" AND ").append(columnName);
return this;
}
@Override
public ResultSet execute() throws SQLException {
PreparedStatement statement = Persistence.prepareStatement(sql.toString());
for(int i = 0; i < values.size(); i++) {
statement.setString(i, values.get(i));
}
return statement.executeQuery();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment