Ivan Ivan - 1 month ago 11
C# Question

Do I understand Open-Closed Principle right?

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?

Answer

Yes, both methods violate the principle.

The first method changes the meaning of Method1, not only showing Hello any more. Your second method extends the first version, which is allowed, but you should have used inheritance to extend the functionality.

There are multiple ways to achieve the 'being closed or open'. Some use inheritance to allow modifications on an entity, others use interfaces. If you'd use interfaces, the second method could also been seen as a violation since it would require a refinement of the interface definition.