...

/

Design by Contract

Design by Contract

Learn about the Design by Contract (DbC) approach to software design.

In this chapter, we'll review different principles that make for good software design. Good quality software should be built around these ideas, and they will serve as design tools. That does not mean that all of them should always be applied; in fact, some of them represent different points of view (such is the case with the Design by Contract (DbC) approach, as opposed to defensive programming). Some of them depend on the context and are not always applicable.

High-quality code is a concept that has multiple dimensions. We can think of this similarly to how we think about the quality attributes of a software architecture. For example, we want our software to be secure and to have good performance, reliability, and maintainability, to name just a few attributes.

Design by contract

Some parts of the software we are working on are not meant to be called directly by users, but by other parts of the code. Such is the case when we divide the responsibilities of the application into different components or layers, and we have to think about the interactions between them.

Press + to interact

We have to encapsulate some functionality behind each component and expose an interface to clients who are going to use that functionality, namely, an Application Programming Interface (API). The functions, classes, or methods we write for that component have a particular way of working under certain considerations that, if they are not met, will make our code crash. Conversely, clients calling that code expect a particular response, and any failure of our function to provide this would represent a defect.

That is to say that if, for example, we have a function that is expected to work with a series of parameters of type integers, and some other function invokes ours by passing strings, it is clear that it should not work as expected, but in reality, the function should not run at all because it was called incorrectly ...