A good utility method
For example, the method convertOzToMl() shown below
accepts an int as its only input and returns an
int as its only output:
// In source packet in file coupling/ex1/Liquid.java
class Liquid {
private static final double FL_OUNCES_PER_ML = 12.0/355.0;
private static final double ML_PER_FL_OUNCE = 355.0/12.0;
/**
* Converts fluid ounces to milliliters
*/
public static int convertOzToMl(int ounces) {
double d = ounces * ML_PER_FL_OUNCE;
d += 0.5; // Must add .5 because (int) truncates
return (int) d; // Result now rounded up if fraction >= .5
}
}
Note that even though the above method makes use of a constant value, the constant value doesn't increase the method's coupling. (This is not only true conceptually, but also in how Java programs are compiled. As mentioned previously in this article, if a class uses a constant, even if it is from another class, its class file gets its own local copy of that constant value.)
To use this method, another method simply passes in the number of ounces and stores the returned number of milliliters:
// In source packet in file coupling/ex1/Liquid.java
class Example1 {
public static void main(String[] args) {
int mlFor8Oz = Liquid.convertOzToMl(8);
int mlFor12Oz = Liquid.convertOzToMl(12);
int mlFor16Oz = Liquid.convertOzToMl(16);
System.out.println("Ml for 8 oz is: " + mlFor8Oz);
System.out.println("Ml for 12 oz is: " + mlFor12Oz);
System.out.println("Ml for 16 oz is: " + mlFor16Oz);
}
}