Loose coupling and returning an object

203 views Asked by At

I have been looking for a while on the Internet about this but could not find an exact answer. Okay, they say inject an abstraction (interface or something) to a class rather than having it to create the instances it needs, or rather than passing an implementing type.

class Foo
{
    private IBar _bar;

    public Foo(Ibar bar)
    {
        _bar = bar;
    }
}

Although I don't fully understand how above is reasonably loosely coupled, but my question at this point is about something else. That is, what if a method has to return an instance of something. How, for example, following can be made loosely coupled:

class Foo
{
    public IBar GetMeSomething()
    {
         return new Bar(); // dependency here
    }
}

I was just wondering how I resolve the above dependency on Bar? Any experienced programmers please help me understanding this. Or someone may be able to suggest some article comprehensively discussing all such scenarios that eliminate/reduce type inter-dependencies.

1

There are 1 answers

0
CoffeDeveloper On

When a class need to know "Something" about your program, you can resolve that by passing a instance of another class in your constructor.

If you accept in constructors only interfaces instead of concrete classes you are later able to change implementation easily.

If you have to create Objects at run time you need factories, you class Foo is in your case a IBarFactory (because it instantiate IBars).

Dependencies in constructors via interfaces are easily resolved by any IoC framework (Factories are passed in constructors too), while the implementation of a factory itself is allowed to instantiate objects directly or through a IoC framework because that's the responsability of the class.

Using IoC containers and dependency injection does not make looscoupling happens for magic, you still have to model classes with SOLID principles in mind, but when using SOLID principles IoC containers and DI are of great help.