Hello,
Say I have an abstract class Connection to represent some kind of connection that can be executed and then return some kind of result. My problem is that the result returned by each connection varies (String, byte[], some other class, etc...). This results in additional logic that seems like it defeats the point of using inheritance in the first place, because I have to downcast the Connection object just to find out what kind of result it returns.
Below is some psuedo code that demonstrates the problem. Any thoughts? There has gotta be a cleaner way of doing something like this:
class ConnectionExecutor {
public void execute(Connection connection) {
// connection.execute();
if (connection instanceof HttpConnection) {
String result = ((HttpConnection) connection).getResponse();
// HttpConnection-specific output logic
}
else if (connection instanceof DatabaseConnection) {
Map<String, String> result = ((DatabaseConnection) connection).getResults();
// DatabaseConnection-specific output logic
}
}
}
abstract class Connection {
// some common connection functionality
}
class HttpConnection extends Connection {
public String getResponse() {
// call web service
// return the string response
}
}
class DatabaseConnection extends Connection {
public Map<String, String> getResults() {
// call database
// return mapped results
}
}