user855
user855

Reputation: 19948

Dependency Injection - Deciding arguments at runtime

I am interested in knowing if the following scenario is a good use case for Dependency injection. The example is a little made up and may not be good OO design. Please bear with me and focus on the part that relates to the question:

Let's say I have the following classes:

class BankAccount
{
    User user;
    Integer accountNo;

    BankAccount(User user, Integer accountNo){
        ....
    }
 }

class User
{
    String firstName, lastName;

    User(String firstName, String lastName)
    {
        ....
    }
}

Let's say I have to create the objects in the following scenario:

void withoutDependecyInjectionUsingNewOperator()
{
     User user = new User("Lance", "Armstrong");
     // These values are determined
     // based on form input on UI
     BankAccount account = new BankAccount(user, 1233);
}

I've come to know of frameworks like Guice or Spring which support DI. If I were using any of these frameworks, should I be changing the above function to use DI?

Based on the examples I have seen so far in tutorials, it seems that it is mostly useful when the constructor arguments can be decided as configuration and not for the cases where the values are ultimately based on User input?

Thanks!

Upvotes: 3

Views: 726

Answers (1)

D Stanley
D Stanley

Reputation: 152644

Based on what you've posted that's not a proper use of dependency injection. It IS a decent case for a factory pattern. Dependency Injection is used to eliminate the dependency on a particular type by using interfaces and only setting the concrete type at runtime (usually using a 3rd party framework like ninject)

For example, you could have an IUserFactory that the BankAccount type uses to get IUsers. At runtime, the BankAccount class could be "injected" with a concrete UserFactory class instead of having a compile-time dependency. You could then swap out UserFactories without having to desire the BankAccount class.

Upvotes: 1

Related Questions