March 2018
Intermediate to advanced
208 pages
4h 52m
English
| | class Distance { |
| » | DistanceUnit unit; |
| » | double value; |
| | |
| | Distance(DistanceUnit unit, double value) { |
| | this.unit = unit; |
| | this.value = value; |
| | } |
| | |
| | static Distance km(double value) { |
| | return new Distance(DistanceUnit.KILOMETERS, value); |
| | } |
| | |
| | void add(Distance distance) { |
| | distance.convertTo(unit); |
| » | value += distance.value; |
| | } |
| | |
| | void convertTo(DistanceUnit otherUnit) { |
| | double conversionRate = unit.getConversionRate(otherUnit); |
| » | unit = otherUnit; |
| | value = conversionRate * value; |
| | } |
| | } |
By default, the state of objects is mutable. Whenever possible, you should make the state immutable because this makes objects harder to misuse.
The code here computes and converts distances ...