I'm currently studying dependency injection and I'm having some issues with the so called 'flexibility' advantage of using dependency injection.
The flexibility advantage is mentioned in post Criticism and disadvantages of dependency injection, where it is mentioned that dependency injection enables "switching implementations quickly (DbLogger instead of ConsoleLogger for example)"
I'm really having qualms about how this 'switching' can occur, and this is probably due to my limited experience. To elaborate on my confusion, I will mainly use constructor injection, which is the one I wish to understand and am working with.
Suppose I have a class User
that depends on a class MsSqlConnection
. According to the above post (and many other articles), it seems as though User
could switch from using MsSqlConnection
to MongoDbConnection
with much greater ease when using dependency injection. But I fail to see that.
Let's consider the following example where constructor injection is used.
class User {
constructor(connection: MsSqlConnection) {}
}
class MsSqlConnection {
constructor() {}
}
const connection_instance = new MsSqlConnection()
const user = new User(connection_instance );
Here, I'm passing connection_instance
as the argument of the constructor of User
. But if I wanted a different kind of connection, say MongoDbConnection
, I will have to declare connection_instance
to be a MongoDbConnection
. It should look like:
const connection_instance = new MongoDbConnection() // changed to MongoDbConnection; note MongoDbConnection class was not defined
const user = new User(connection_instance);
However, in addition to creating a connection_instance
of type MongoDbConnection
, the above code would simply not work. This is because our User
class looks like
class User {
constructor(connection: MsSqlConnection) {}
}
and the constructor of User
only takes an argument of type MsSqlConnection
, not of type MongoDbConnection
. So where is the flexibility? I would have to adapt my constructor and change the code inside of User
to adapt to MongoDbConnection
.
I feel like I might be missing something rudimentary here... Any answers are very appreciated, and it'd be even greater if they are catered to some beginner (like me).
: MsSqlConnection