What you could try is to make helper methods that require the user actions to be supplied as a lambda expression or method reference. I’m not sure how you’re connecting to SQLite, so I’ll use JDBC classes in my example:
public static void doAction(Consumer<Connection> userAction) {
try (Connection conn = /* logic to create connection */) {
userAction.accept(conn);
}
// Connection automatically closed due to try-with-resources
}
A user could then do the following:
SqliteHelper.doAction(conn -> {
// Logic that uses connection
});
One problem with this approach is that Consumer
requires you to catch exceptions within the lambda body. If this isn’t what you want you could define your own functional interface that allows exceptions:
@FunctionalInterface
public interface SqliteOperation {
void perform(Connection connection) throws SQLException;
}
The doAction
method then needs a slight tweak:
public static void doAction(Consumer<Connection> userAction) {
try (Connection conn = /* logic to create connection */) {
userAction.accept(conn);
} catch (SQLException e) {
// Log the error, wrap it in another exception, just don't ignore it
}
// Connection automatically closed due to try-with-resources
}
CLICK HERE to find out more related problems solutions.