Frage

Does an OOP design that uses a Design by Contract mean the designer is using interfaces to create a "contract." The term "contract" is used quite often when discussing OOP interfaces, so I didn't know if these were talking about the same concept when using the word "Contract."

What I want to do in one of my designs is to force the class sending a message to do so based upon implementing an interface. For example,

class MyClass
{
  IMyInterfact someKindOfThing;
  public MyClass(IMyInterface something)
  {
        this.someKindOfThing = something;
  }

}
War es hilfreich?

Lösung

Not quite. Interfaces are rather limited in the amount and kind of contract information they can provide.

For example, the interface:

interface ISizeable
{
    public int Size;
}

tells you that the "contract" has a Size member, but doesn't tell you anything else about that value, like how big or small it is allowed to be.

Normally, size is not negative. You could solve this problem by making it an unsigned int, but that only works for sizes, and doesn't constrain the positive value. You can create a specific type that will only accept values within a specified constraint range, but now you're just pushing the problem somewhere else.

Microsoft Code Contracts takes a different approach:

Contract.Requires( x != null );
Contract.Ensures( this .result > 0 );

Code Contracts contains a static analyzer, so the compiler can actually identify conditions under which contracts will never be fulfilled.

Lizenziert unter: CC-BY-SA mit Zuschreibung
scroll top