In this exercise we will look at how to apply the SOLID principles in code.
✏️ Investigate the ControlUnit.PollSensors()
method. What are its current responsibilities? (No need to do anything, just make sure you find all responsibilities before you continue). Ask an instructor if you're not sure.
📖 Instead of "newing up" sensors in a list when we call pollSensors()
, we want to pass a collection of sensors in to the ControlUnit somehow (we want to invert the dependencies between ControlUnit, pollSensors callee, and the various Sensor classes). However, we don't want to pass the sensors in when we are polling. When we poll sensors, the control unit should be configured with all of the required sensors.
✏️ Use Dependency Inversion by sending a list of sensors in as a constructor parameter when we're creating the ControlUnit
class.
✏️ Investigate the pollSensors method again, same as #1. What are the responsibilities now? (Not sure? Ask an instructor!).
❓ You didn't forget test coverage of ControlUnit or leave failing tests did you?
As you try to write tests for ControlUnit.PollSensors(), you might find it frustrating that it doesn't return any value. Here's a couple of workarounds:
⭐ At the moment we're just writing messages using Console.WriteLine
which is impossible to test. What if you made an AlarmHandler
interface with the method HandleTriggeredSensor(Sensor sensor)
or HandleTriggeredSensor(String sensorOutput)
?
The default implementation (ConsoleWritingAlarmHandler
? (Just suggestions...)) could then do the Console.WriteLine
calls as before, but in your tests you could implement a FakeAlarmHandler
class that stores all
sensor logs in a List which you can then read and assert against in your test.
⭐ Nobody said PollSensors
has to return void. It's your implementation after all. If you want to return a Dictionary<string, string>
of sensor id's and sensor alarm messages so that it's easier to test, go for it.