Currently I am working on the Racing-Car-Katas. The goal is to refactor a peach of code so that it follows the solid-principles.
I try to add the Dependency Inversion Principle. Where I can pass a dependency through the constructor.
Initial Situation
Insid the class Alarm
is the dependency Sensor
which generates a psiPressureValue
.
public class Alarm {
Sensor sensor = new Sensor();
public void check()
{
double psiPressureValue = sensor.popNextPressurePsiValue();
/* ... */
}
}
Idea
public class Alarm {
Sensor sensor;
public Alarm() {
this.sensor = new Sensor();
}
public Alarm(ISensor sensor) {
this.sensor = sensor;
}
public void check()
{
double psiPressureValue = sensor.popNextPressurePsiValue();
/* ... */
}
}
If this would be a real application I don't want to break any dependency between Alarm
and Sensor
. There for I would created the following constructor
public Alarm() {
this.sensor = new Sensor();
}
But my gut feeling says this is code small..
How to handle such dependencies in real world applications?
Aucun commentaire:
Enregistrer un commentaire