Many times I want to define an interface with some methods that maintain a behavior relationship between them.
However, I feel that many times this relationship is implicit. With that in mind, I asked myself: Is there any way to enforce a behavior relationship between interface methods?
I thought about defining this behavior via inheritance (by defining a common implementation). But since C# does not allow multiple inheritance, I believe that many times an interface would be more advisable and that inheritance is not flexible enough.
For example:
public interface IComponent
{
void Enable();
void Disable();
bool IsEnabled();
}
For this interface, I wanted the following relationship to be fulfilled:
- If
Enable()
is called,IsEnabled()
should return true. - If
Disable()
is called,IsEnabled()
should return false.
In that example, the behavior constraint that I would want to enforce is:
- When implementing
Enable()
, the implementer should ensure thatIsEnabled()
returns true - When implementing
Disable()
, the implementer should ensure thatIsEnabled()
returns false
Is there a way to enforce this implementation constraint? Or, the fact that I am thinking about enforcing this kind of constraint is itself a sign that there is a flaw in the design?
Enable()
fails, doesIsEnabled()
then lie and returntrue
?