Consider the following interfaces in C#:
public interface IUpgradeable
{
public void Upgrade();
}
public interface ISpeedUpgradeable : IUpgradeable
{
public int GetCurrentSpeed();
}
public interface IDamageUpgradeable : IUpgradeable
{
public float GetCurrentDamage();
}
And the following class that implements them:
public class SpaceShip : ISpeedUpgradeable, IDamageUpgradeable
{
public int GetCurrentSpeed()
{
return 0;
}
public float GetCurrentDamage()
{
return 0f;
}
public void Upgrade()
{
//Which Upgrade am I implementing? ISpeedUpgradeable? or IDamageUpgradeable?
}
}
Since both ISpeedUpgradeable
and IDamageUpgradeable
both extend IUpgradeable
, shouldn't they both have implementations of Upgrade()
each? or am I misunderstanding how inheritance in interfaces work?
CodePudding user response:
There is only one meaning of IUpgradeable
. The fact that multiple interfaces inherit it, and add meaning to themselves doesn't change the meaning of the original interface. Your class simply implements ISpeedUpgradeable
, IDamageUpgradeable
, and IUpgradeable
: it doesn't implement a specific flavor of IUpgradeable
.
The Upgrade()
method should only mean what it means to the IUpgradeable
interface. Think about your business model (or in this case probably a game model): is there an item floating around that "upgrades" anything upgradeable that it comes in contact with? Does upgrading the ship mean upgrading its speed, or damage, or both? If simply calling Upgrade
doesn't provide enough information to match the way your business model works, you may need to re-think your interface design.