4

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;
  }

}
3
  • 1
    Interfaces are generally mentioned in a "Design by Contract" approach because they force the inheriting class to use the properties and methods. Abstract classes and inherited classes will also enforce "rules" on an inherited class. Nov 21, 2016 at 22:03
  • DbC is something more than a simple interface. What your code is doing is a simple dependency injection through the constructor.
    – Laiv
    Nov 21, 2016 at 22:20
  • 1
    en.wikipedia.org/wiki/Design_by_contract
    – user188153
    Nov 21, 2016 at 22:56

1 Answer 1

4

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.

2
  • Robert, Is this a norm in programming? Is Design by Contract a common practice?
    – johnny
    Nov 22, 2016 at 16:44
  • 2
    I haven't seen it used much, but I'm just one person. As with all things in computing, you use it when you need the benefits it provides. Nov 22, 2016 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.