Search code examples
c#dependency-injectionloose-coupling

Tightly or loose coupled with static methods


public Interface IFoo()
{
    void DoSomething();
}

public class Foo
{
    private IFoo _ifoo;

    public Foo(IFoo foo)
    {
        _ifoo = foo;
    }

    public void Bar()
    {
        // execute
        _ifoo.DoSomething();
    }
}

In the above example - I am using dependency injection via interfaces decoupling a dependency

VS

In this scenerio are the classes tightly coupled by using a class with static methods?

public class Foo
{
    public static void GenerateSomeFoo(){
        //do something here
    }
}

public class FooBar 
{
    public void Bar()
    {
        var somevariable = 123;
        Foo.GenerateSomeFoo();
    }
}

Solution

  • are the classes tightly coupled by using a class with static methods?

    Yes.

    In your example, Foo.GenerateSomeFoo() is being called inside of the FooBar class, which makes it more difficult to swap the implementation of GenerateSomeFoo() if you need to use an alternate implementation for some reason. Therefore, FooBar is tightly coupled to Foo.GenerateSomeFoo().

    Static methods are by their nature tightly coupled to the code that calls them, so you should avoid putting any logic in static methods that could now or in the future receive injected dependencies.

    However, that doesn't mean that you should never use static methods. Extension methods in particular are extremely useful. It is just not very practical to inject dependencies into them, and they tend to make testing more difficult.