SOLID: Sensor Has ID¶
Consider the following Sensor
hierarchy (and imagine that there
are many more implementations like W1Sensor
out there that
implement the Sensor
interface).
#pragma once
class Sensor
{
public:
virtual ~Sensor() {}
virtual double get_temperature() = 0;
Sensor(unsigned int id) : _id(id) {}
// unused, mostly
unsigned int id() const { return _id; }
private:
// unused, mostly
unsigned int _id;
};
#pragma once
#include "sensor.h"
#include <cstdint>
class W1Sensor : public Sensor
{
public:
W1Sensor(unsigned int id, uint64_t w1_address)
: Sensor(id),
_w1_address(w1_address) {}
double get_temperature() override
{
// ... access physical sensor ...
return 36.5;
}
private:
uint64_t _w1_address;
};
Here is a sampe usage of the W1Sensor
class.
#include "sensor-w1.h"
#include <unistd.h>
#include <iostream>
int main()
{
W1Sensor sensor(/*id*/ 666, // unused in this program
/*w1_address*/ 0xdeadbeefUL);
while (true) {
double temperature = sensor.get_temperature();
std::cout << temperature << std::endl;
sleep(1);
}
return 0;
}
Obviously the id
attribute of a sensor remains unused in most
situations.
Which of the five SOLID principles are violated? Which are not? Comment!
Principle |
Why violated? |
Why not? |
---|---|---|
Single Responsibility |
||
Open/Closed |
||
Liskov Substitution |
||
Interface Segregation |
||
Dependency Inversion |