I have this inteface:
public interface ICommand
{
bool Execute(Vector2 commandPosition);
bool Execute(GameUnit gameUnit);
bool Execute(string shortcut);
}
And a class with these methods making same things with different argument types
private void DispatchGameUnitCommand(GameUnit gameUnit)
{
if (_preparedCommand != null)
{
_preparedCommand.Execute(gameUnit);
return;
}
for (int i = 0; i < _commands.Length; i++)
{
if (_commands[i].Execute(gameUnit))
{
return;
}
}
}
private void DispatchLocationCommand(Vector2 screenPosition)
{
if (_preparedCommand != null)
{
_preparedCommand.Execute(screenPosition);
return;
}
for (int i = 0; i < _commands.Length; i++)
{
if (_commands[i].Execute(screenPosition))
{
return;
}
}
}
private void DispatchShortcutCommand(string shortcut)
{
if (_preparedCommand != null)
{
_preparedCommand.Execute(shortcut);
return;
}
for (int i = 0; i < _commands.Length; i++)
{
if (_commands[i].Execute(shortcut))
{
return;
}
}
}
How could I improve them removing duplicated code? Is it possible in anyways?
Your post says you have "a class with these methods" for
GameUnit,Vector2andstring.All indications in your code sample are that an actual
GameUnitis required to do anything. In this case, the thing that "might" really help is having implicit conversion operators that turn astringor aVector2into aGameUnit.GameUnitwith implicit conversionsFollowing this logic, we end up with a dispatcher class that needs only one method not three.
As for the
interface, how were you planning on using it? So far, it's not needed for anything.Testing