There is something I do not understand about open-close principle. Let's say that you have done this code:
public abstract class Player
{
public string Name { get; set; }
public int Level { get; set; }
}
public sealed class Fighter : Player { /* ... */ }
public sealed class Warrior : Player { /* ... */ }
This code works perfectly, you've done a first release, eveyrthing is OK.
Now you want to add some features, like a player can equip a ring. Open-close principle says open to extension, close to modification. How could I implement the fact that my players can have rings if I shouldn't modify these class?
You can modify class Player
by adding new methods and fields. It is open to extension. But if you already have some methods like Jump
or Fight
and you want to modify them - that is breaking the principle.
Imagine, your class Fighter
has method Fight()
and it uses only bare hands:
public Fighter() : Player
{
...
public virtual void Fight()
{
//use bare hands
}
}
If you want Fighter
to fight with a stick (for example) you should not modify initial method Fight()
but add another class like FighterWithStick : Fighter
and override method Fight()
there:
public FighterWithStick() : Fighter
{
...
public override void Fight()
{
//use stick
}
}