I am very familiar with functional langauges such as Scheme, and Haskell. I’m trying to solve a problem in Java and struggling, possibly because I’m still in a functional mindset.
I want to write:
public void doQueryAndStoreData(String query, <? extends Collection> storeIn) {
/* make a jdbc query, get ResultSet */
ResultSet rset = ...;
ProcessResultSet proc = new ProcessResultSet();
proc.process(rset, storeIn);
/* clean up */
}
with an interface like:
private interface IProcessResultSet<C> {
public void process(ResultSet rset, C storeIn);
}
and a class implementing the interface like:
private class ProcessResultSet implements IProcessResultSet<? extends Collection> {
public void process(ResultSet rset, Map storeIn) {
/* do something */
}
public void process(ResultSet rset, List storeIn) {
/* do something else */
}
}
so that the first method can call the appropriate process based on what type of storeIn it’s given.
In Haskell I could write
class Storeable c a where
store :: a -> c a -> c a
doQueryAndStoreData :: Storeable c a => ResultSet a -> c a -> c a
doQueryAndStoreData (ResultSet rs) coll = foldr store coll rs
and provide Storeable instances for whatever collection type I want to store my ResultSet in.
Is this the correct approach in Java? Because I feel like I’m somewhat fighting the langauge to accomplish this.
No, Java doesn’t do that.
You’d need to do something like:
Or much more likely:
I hope I don’t need to mention SQL injection vulnerabilities are a bad thing. (Also
Mapis not aCollectionin Java (it is in C# but C#Collectionisn’t very useful).)