📜 ⬆️ ⬇️

[C ++] Contract Design and the LSP Principle on the Example “Why a Class Man cannot be a subtype of the Fireplace class”

The Liskov Substitution Principle (LSP) and Contract Design (DbC) are well explained in this English-language PDF.

I will explain in 2 words what it is:
DbC : functions are provided with preconditions and postconditions. The function starts its execution only if the preconditions are satisfied. After its completion, the function will guarantee that the postconditions and invariants of the class will be met / consistent.

LSP is one way to determine if one class can be a subtype of another. Based on IS-A relationship. Only not in terms of external similarity of classes, but in terms of their behavioral substitutability when using the reference to the base class of the object of the derived class.
')
Using the example code, I’ll show why the Human class cannot be inherited from the Fireplace class.

#include <iostream>
#include <cassert>

class Fireplace {
public :
// (.. ) 18
Fireplace() : temperature(18) { }

// -
int getTemperature() const {
return temperature;
}
// -
void setTemperature( int N) {
temperature = N;
}

// N
virtual void heat( int N) {
// preconditions
int old_temperature = getTemperature();
// 800
assert(getTemperature() + N < 800);

std::cout << " " ;
setTemperature(getTemperature() + N);

// postconditions
// + N
assert(getTemperature() == old_temperature + N);
}
private :
int temperature;
};

class Human : public Fireplace {
public :
Human() { setTemperature(36); }

virtual void heat( int N) {
// preconditions
int old_temperature = getTemperature();

assert(getTemperature() + N < 800); // assert , ..
// 800 -

// 45
// assert:
// assert(getTemperature() + N < 45);
//
// !

// DbC:
// 1) ,
// 2) ,

// - Human Fireplace
// .. LSP,
// /
//


std::cout << " " ;
setTemperature(getTemperature() + N);

// postconditions . .
// + N
assert(getTemperature() == old_temperature + N);
}
};

int main()
{
Fireplace *f = new Human;
f->heat(600);

return 0;
}


* This source code was highlighted with Source Code Highlighter .


By the way, if the fireplace could only heat up to 45 degrees - then from the LSP’s point of view, it could be a Fireplace subtype :)
I would be glad if the article helped someone, clarified these principles a little bit.

Source: https://habr.com/ru/post/72907/


All Articles