Home > Software engineering >  Make a generic function in Java
Make a generic function in Java

Time:11-05

I have two methods to get data from the database. They differ only in the request and the return type. Is it possible to combine them somehow so that the code does not repeat itself?

public ObservableList<Car> getAllCars() {
    ObservableList<Car> list = FXCollections.observableArrayList();
    Connection connection = MyConnection.connection;
    String query = "SELECT * FROM cars";
    try {
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(query);
        while (rs.next()) {
            Car car = new Car(rs.getInt("ID"), rs.getInt("STYLE_ID"),
                    rs.getString("MAKE"), rs.getString("MODEL"),
                    rs.getInt("YEAR"), rs.getInt("PRICE"));
            list.add(car);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return list;
}

public ObservableList<Style> getAllStyles() {
    ObservableList<Style> list = FXCollections.observableArrayList();
    Connection connection = MyConnection.connection;
    String query = "SELECT * FROM styles";
    try {
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(query);
        while (rs.next()) {
            Style style = new Style(rs.getInt("ID"), rs.getString("NAME"));
            list.add(style);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return list;
}

CodePudding user response:

You can first write a functional interface that represents a function that converts a ResultSet to some type T:

@FunctionalInterface
interface ResultConverter<T> {
    T convert(ResultSet resultSet) throws SQLException;
}

Then you can write a common function that takes a ResultConverter<T>:

public <T> ObservableList<T> getAll(ResultConverter<T> converter, String query) {
    ObservableList<T> list = FXCollections.observableArrayList();
    Connection connection = MyConnection.connection;
    try {
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(query);
        while (rs.next()) {
            T t = converter.convert(rs);
            list.add(t);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return list;
}

Then you can leave the non-duplicated parts in getAllStyles and getAllCars:

// getAllCars:
return getAll(rs -> new Car(rs.getInt("ID"), rs.getInt("STYLE_ID"),
                rs.getString("MAKE"), rs.getString("MODEL"),
                rs.getInt("YEAR"), rs.getInt("PRICE")),
              "SELECT * FROM cars");

// getAllStyles:
return getAll(rs -> new Style(rs.getInt("ID"), rs.getString("NAME")),
              "SELECT * FROM styles");
  • Related