I’ve got two methods to extract data out of a CSV
private Car processCar (String [] row) {
Car c = new Car();
c.setCarId(Integer.parseInt(row[CSVColumns.carid.index]));
....
return c;
}
private Driver processDriver(String[] row) {
Driver d = new Driver(row[CSVColumns.name.index]);
sys.setAge(row[CSVColumns.age.index]);
...
return d;
}
Now, while extracting data out of the database I need to again make these two methods, however, with slight changes
private Car processCar (ResultSet rs) {
Car c = new Car();
c.setCarId(rs.getInt("Id"));
....
return c;
}
private Driver processDriver(ResultSet) {
Driver d = new Driver(rs.getString("Name));
sys.setAge(rs.getString("Age"));
.....
return d;
}
Is there a way to simplify this so that I don’t have to repeat myself? Additionally, each method contains a lot of getters/setters so I would hate to copy paste stuff and make changes…
Abstract data source and use common interface
The idea is to have common adapter that translates either
ResultSetor CSV into something common behind consistent interface:And two implementations:
and this is how you use it:
Providing either
new CsvDataSource()ornew ResultSetDataSource().Abstract factory with two implementations:
Very similar approach, create and abstract factory:
With two implementations:
Combination
I don’t like any of the approach above since they introduce a lot of boilerplate without adding much value. But the first approach is promising once you reduce it.
Have just one
processCar()that takesString[]as an argument. However if you have aResultSet, simply translate it first toString[]by extracting columns into subsequent items in arrays:The translation in the other direction so that
ResultSetis the base format is also possible, butResultSetis much harder to implement alone.