I want to understand how Dependency Inversion gets rid of switch cases.
Consider a service that needs to communicate with several databases.
class StockUpdater {
private final DataStore datastore;
public StockUpdater(DataStore datastore) {
this.datastore = datastore;
}
public void update(StockItem item, int quantity){
datastore.update(item, quantity);
}
}
public interface DataStore {
update(StockItem item, int quanity)
}
public class PostgresAdapter implements DataStore {
...
public void update(StockItem item, int quantity) {
// Add item to database
}
}
public class MariaDBAdapter implements DataStore {
...
public void update(StockItem item, int quantity) {
// Add item to database
}
}
We remembered our friend abstraction and used interface. Whereas in the past, we might have used hideous if/else or switch statements instantiating for instances new MariaDBAdapter.
Now I understand that we solved this issue by using an interface and taking the logic (if/else conditions ) out of the class stockUpdater and the update() method; however, I thought we shift the problem. Since we need to provide a Datastore when we create a StockUpdater. And this needs an again a condition when to create a PostgresAdapter or a MariaDBAdapter.
it would just be
DataStore myDatastore = null
if (...){
myDatastore = new PostgresAdapter()
}
else {
myDatastore = new MariaDBAdapter()
}
StockUpdater myUpdater = new StockUpdater(myDatastore)
...
If my goal is to get rid of tedious if/else conditions, this looks quite the same. If I wanted to take the logic out of StockUpdater, then sure, this is great.
I hope I made myself clear. I might have a thinking blockage. My question how did Dependency Inversion gets rid of switch cases? Or what I am missing in my reasoning.
Class c = Class.forName(className); Object o = c.newInstance();That way the config file determines which one is created.