Do I understand the principle of open closure?

Say, in the first version of my hypothetical software, I have a simple class:

public Class Version1
{
    public void Method1()
    {
       Console.WriteLine("Hello");
    }
}

In the second version, I have an update that requires a modification of method 1 as follows:

public Class Version1
{
    public void Method1()
    {
       Console.WriteLine("Hello");
       Console.WriteLine("World");
    }
}

And in the third version, I have an update that requires adding another method to this class as follows:

public Class Version1
{
    public void Method1()
    {
       Console.WriteLine("Hello");
       Console.WriteLine("World");
    }

    public int Method2()
    {
        return 7;
    }    
}

Now, to my understanding of the Open-Closed principle, in both updates I violated this principle because I modified the class that performed the desired work in the first version of my software.

I think this needs to be done, but not sure if this is correct:

public virtual Class Version1
{
    public virtual void Method1()
    {
       Console.WriteLine("Hello");
    }
}

public virtual Class Version2 : Version1
{
    public override void Method1()
    {
       Console.WriteLine("Hello");
       Console.WriteLine("World");
    }
}  

public Class Version3 : Version2
{      
    public int Method2()
    {
        return 7;
    }

}

How is it wrong / right?

+4
source share
1

, .

Method1, Hello. , , .

" ". , . , , .

+4

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


All Articles