Java 11 Cookbook
上QQ阅读APP看书,第一时间看更新

There's more...

With the getWeightKg(int pounds) method accepting the input parameter, the method name can be misleading because it does not capture the weight unit of the input parameter. We could try and name it getWeightKgFromPounds(int pounds) but it does not make the method function clearer. After realizing it, we decided to make the convertPoundsToKg(int pounds) method public and to remove the getWeightKg(int pounds) method at all. Since the convertPoundsToKg(int pounds) method does not require access to the object fields, it can be static, too:

public interface Truck extends Vehicle {
int getPayloadPounds();
default int getPayloadKg(int pounds){
return convertPoundsToKg(pounds);
}
static int convertKgToPounds(int kilograms){
return (int) Math.round(2.205 * kilograms);
}
static int convertPoundsToKg(int pounds){
return (int) Math.round(0.454 * pounds);
}
}

Fans of the metric system are still able to convert pounds into kilograms and back. Besides, since both converting methods are static, we do not need to create an instance of the class that implements the Truck interface in order to do the conversion: 

public static void main(String... arg) {
int payload = Truck.convertKgToPounds(1500);
int vehicleWeight = Truck.convertKgToPounds(1800);
System.out.println("Weight in pounds: " + vehicleWeight);
int kg = Truck.convertPoundsToKg(vehicleWeight);
System.out.println("Weight converted to kg: " + kg);
System.out.println("Weight converted back to pounds: " +
Truck.convertKgToPounds(kg));
}

The results do not change: