Let's say in first version of my hypothetical software I have a simple class like this:
public Class Version1
{
public void Method1()
{
Console.WriteLine("Hello");
}
}
In second version, I have an upgrade that requires the Method 1 to be modified like this:
public Class Version1
{
public void Method1()
{
Console.WriteLine("Hello");
Console.WriteLine("World");
}
}
And in third version, I have an upgrade which requires adding another method to this class like this:
public Class Version1
{
public void Method1()
{
Console.WriteLine("Hello");
Console.WriteLine("World");
}
public int Method2()
{
return 7;
}
}
Now, to my understanding of Open-Closed principle, in both upgrades, I have violated this principle because I modified the class that was doing desired work in the first version of my software.
The way I think it should be done, but not sure if correct, is like this:
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 wrong/right is this?