Liskov Substitution Principle & Contracts
When working with contracts, there are several unpleasant things that you have to work around. For example, the Liskov Substitution Principle, which Contracts developers adhere to, is not mentioned by night.
For example, we have a certain class that inherits an interface from an external library. And we define in the class the implementation of the method from this interface:
So, the ambush is that according to the principles described above, we should not directly check the incoming values, because it is the responsibility of the postconditions of the library, the interface provider. Those. a similar code is considered incorrect:
Moreover, even such an implementation will generate a warning (warning CC1033):
Apparently, the developers hope that the creators of the interfaces understand a little more than usual in the rules of inheritance and the theory of building hierarchies ...
PS. It is necessary to use the old method of validation instead of contracts in the processing of such inherited interfaces, removing the contract specification.
For example, we have a certain class that inherits an interface from an external library. And we define in the class the implementation of the method from this interface:
public class A : Interface1
{
public void MethodInterface1( object sender, Event e) {...}
}
So, the ambush is that according to the principles described above, we should not directly check the incoming values, because it is the responsibility of the postconditions of the library, the interface provider. Those. a similar code is considered incorrect:
public void MethodInterface1( object sender, Event e)
{
Contract.Requires(sender != null, "Sender is null");
Contract.Requires(event != null, "Event object is null");
...
}
Moreover, even such an implementation will generate a warning (warning CC1033):
public void MethodInterface1( object sender, Event e)
{
if (sender == null) throw new ArgumentNullException("sender", "Event sender is null.");
if (evt == null) throw new ArgumentNullException("evt", "Event object is null.");
Contract.EndContractBlock();
...
}
Apparently, the developers hope that the creators of the interfaces understand a little more than usual in the rules of inheritance and the theory of building hierarchies ...
PS. It is necessary to use the old method of validation instead of contracts in the processing of such inherited interfaces, removing the contract specification.