Skip to content

Instantly share code, notes, and snippets.

@mcsee
Last active August 16, 2025 02:02
Show Gist options
  • Save mcsee/5bae947aa6410789541e18ab9f4e24b8 to your computer and use it in GitHub Desktop.
Save mcsee/5bae947aa6410789541e18ab9f4e24b8 to your computer and use it in GitHub Desktop.
This gist belongs to Clean Code Cookbook http://cleancodecookbook.com By Maximiliano Contieri http://maximilianocontieri.com
public class DatabaseConnection {
public Object execute(String sql) {
if (sql.startsWith("SELECT")) {
return new ResultSet();
} else if (sql.startsWith("INSERT")) {
return Integer.valueOf(42);
} else if (sql.startsWith("UPDATE")) {
return Boolean.TRUE;
}
return null;
// The billion dollar mistake
}
}
public class QueryHandler {
public void handle(String sql, DatabaseConnection db) {
Object result = db.execute(sql);
// The caller needs to be aware of many different types
if (result instanceof ResultSet) {
System.out.println("Fetched rows");
} else if (result instanceof Integer) {
System.out.println("Inserted " + result);
} else if (result instanceof Boolean) {
System.out.println("Updated " + result);
} else {
System.out.println("Unknown result");
}
}
}
// This second class has a method execute()
// which is NOT polymorphic since it returns
// another types
public class NonRelationalDatabaseConnection {
public Object execute(String query) {
if (query.startsWith("FIND")) {
return new Document();
} else if (query.startsWith("INSERT")) {
return Integer.valueOf(1);
} else if (query.startsWith("UPDATE")) {
return Boolean.TRUE;
}
return null; // The billion dollar mistake
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment