Proper use of YAGNI dependency injection and confusion in C #

I know that you should depend on abstractions and not on specific implementations, but I also know the YAGNI principle . Sometimes I try to come to terms with this.

Consider the following classes:

public class Foo
{
    public void DoFoo()
    {
    }
    //private foo stuff
}

public class Bar
{
    private readonly Foo _foo;

    public Bar()
    {
        _foo = new Foo();
    }
}

A bar is a class that interests me; obviously there is a problem, Bar creates an instance of Foo, so let me refactor;

public class Bar
{
    private readonly Foo _foo;

    public Bar(Foo foo)
    {
        _foo = foo;
    }
}

Great, but the Bar constructor still depends on Foo, the concrete implementation. I got nothing (right?). To fix this, I need to make foo an abstraction, and this is where my problem starts.

, (), , . , , , Foo ( ). "IFoo" "FooBase", , YAGNI? - , , ,

public abstract class Foo
{
    public abstract void DoFoo();

    //private foo stuff
}

public class Foo1:Foo
{
    public override void DoFoo()
    {
    }
}

Bar, , "I" ( ), .

public interface Foo
{
    void DoFoo();
}

public abstract class FooBase:Foo
{
    public abstract void DoFoo();

    //private foo stuff
}

public class Foo1:FooBase
{
    public override void DoFoo()
    {
    }
}

, ( , )?

. "I", . , Foo , , , DI , DI, , , Foo.

+4
3

Bar Foo, . ( ?).

, , Foo - , , Foo.

, Foo ( )

. -, ( ) . , .

"IFoo" "FooBase", , YAGNI?

YAGNI, . YNI ( ). , . , , ( ) , (.. ).

,

, , , , . , . , . , (, ) (). , .

+4

, , , .

DI ? Unity, PRISM , ViewModels BindableBase ( Base, PRISM), , .

, BaseViewModel, BindableBase INotifyDataErrorInfo . , , ViewModels BaseViewModel.

+2

Foo Bar - - Bar, . , Bar, , Foo , , , . unit test Foo, , Bar , , , , Foo Bar . DI - , Foo, Foo DI.

+1
source

Source: https://habr.com/ru/post/1659076/


All Articles