Saturday, 21 January 2023

Contracts.

Introduction.

Design by Contract is the Software Collaboration Method.

Contract / between class user and class author / should state under which condition class will provide it's services to class user, and what these services are.


Contract.

There are Preconditions, Postconditions and Invariants that regulate contract.

Precondition is a condition that is required for something to happen. Precondition can be simple or complex, complex precondition consists of multiple simple or complex preconditions as well.

Postcondition is something that is guaranteed to happen if preconditions are met & program behaves correctly.

Invariants is something that is guaranteed to hold, at least in observable moments in time, or perhaps even all the time.


If class user provides 'correct' / or using alternative wording: 'legal' / preconditions to object, methods will ensure that postconditions are met.

Invariants are always met / though some disagree, for there's 'observable moment' argument /, or contract is broken.


Examples for Preconditions:

- requirements for method arguments allowed values,
- concurrency requirements,
- perhaps more.


Examples for Postconditions:

- program's process(-es) will compute and provide results correctly,
- program will finish within the agreed time frame in at least 90% of situations,
- perhaps more.


Examples for Invariants:

- heat in Reactor will never go above the Critical Value,
- variable 'divisor' will never have '0' value,
- variable 'divisor' will never have '0' value during computations phase,
- perhaps more.


Inheritance / in simple words /.

To not break contract, following conditions must be met:

1. subclasses must require no more than it's neccessary for superclass to work correctly / but can require less /.

2. subclasses must meet all requirements of superclass / but perhaps can give more /.

This is related with the Liskov's Substitution Principle / LSP /.


Exceptions in Java.

When contract is broken during Runtime, an Exception should be thrown.


No comments:

Post a Comment