6. Improving the semantics inside Alarm and adding a new concept to enrich the domain.Now we turn our attention to the code inside the Alarm class.
We first rename a local variable inside the check method and the method we are calling on Sensor so that we have new names that have less to do with the implementation of Sensor.
Next, we extract the condition inside the check method to an explanatory helper: isNotWithinSafetyRange.
This is the resulting code:
Notice that the Alarm class contains a data clump.
The constants LowPressureThreshold and HighPressureThreshold don't make any sense the one without the other. They together define a range, to which we have already referred both in production and test code as a safety range.
We remove the data clump by creating a new concept, the SafetyRange value object:
7. Moving Specificity Towards the Tests.If you check the tests in AlarmShould class, you'll see that it's difficult to understand the tests at a glance.
Why is the alarm on in some cases and off in some other cases?
To understand why, we have to check Alarm's constructor in which a SafetyRange object is created. This SafetyRange is an implicit configuration of Alarm.
We can make the code clearer and more reusable by moving this configuration details towards the tests.
J. B. Rainsberger explains this concept of moving specificity towards the tests in this video which is embedded in his Demystifying the Dependency Inversion Principle post.
So we change the signature of the Alarm constructor so that the SafetyRange is injected through it.
Now the configuration detail is explicit and it's easier to understand at a glance why any test pass or not.
Moreover this change makes Alarm more reusable.
This is the third post in a series of posts about solving the Tire Pressure Monitoring System exercise in Java:
- Solving the Tire Pressure Monitoring System exercise (I)
- Solving the Tire Pressure Monitoring System exercise (II)
- Solving the Tire Pressure Monitoring System exercise (III)
- Solving the Tire Pressure Monitoring System exercise (IV)