I have a CustomObject class which has the abilities like being Clickable, KeyPressable and Movable. I created interfaces: IClickable, IKeyPressable and IMovable and make different CustomObject classes to implement them. For example;
public class ClickableObject: IClickable {...}
public class MovableObject: IMovable {...}
public class ClickableAndMovableObject: IClickable , IMovable {...}
But I’m thinking now that I can do it with one class and less lines like below;
public class CustomObject
{
public bool isClickable;
public bool isMovable;
public bool isKeyPressable;
// OnClick, OnMove and OnKeyPress events and other functions.
}
and use this bool values if they are clickable or movable etc.
I am not sure which is the correct way to do.
If the interfaces are empty and you find yourself querying:
if (someObject is IClickable)
{
...
}
then those interfaces are probably not very useful and can be replaced by boolean values.
If on the other hand the interfaces contain members which are actively used, for example:
clickableObject = someObject as IClickable;
if (clickableObject != null)
{
clickableObject.Click(this.coordinates);
}
then it makes perfect sense to use interfaces. If you are afraid of code duplication, make an abstract class inherited by any object which uses one of your interfaces. In this abstract class, create properties such as:
protected bool IsClickable
{
get
{
return this is IClickable;
}
}
protected bool AsClickable
{
get
{
return this as IClickable;
}
}
or go fancy with:
protected bool RunIfClickable(Action<IClickable> action)
{
var clickable = this.AsClickable;
if (clickable != null)
{
action(clickable);
}
}
which makes the earlier example as easy as:
someObject.RunIfClickable(c => c.Click(this.coordinates));
8