In this item, Mr Bloch mention about same symptom I have faced previously and shared in this post.
The constant interface pattern is a poor use of interfaces:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Constant interface antipattern - do not use! | |
public interface PhysicalConstants { | |
// Avogadro's number (1/mol) | |
static final double AVOGADROS_NUMBER = 6.02214199e23; | |
// Boltzmann constant (J/K) | |
static final double BOLTZMANN_CONSTANT = 1.3806503e-23; | |
// Mass of the electron (kg) | |
static final double ELECTRON_MASS = 9.10938188e-31; | |
} |
Instead use a utility class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Constant utility class | |
package com.effectivejava.science; | |
public class PhysicalConstants { | |
private PhysicalConstants() { } // Prevents instantiation | |
public static final double AVOGADROS_NUMBER = 6.02214199e23; | |
public static final double BOLTZMANN_CONSTANT = 1.3806503e-23; | |
public static final double ELECTRON_MASS = 9.10938188e-31; | |
} |
If you make heavy use of the constants exported by a utility class, you can avoid the need for qualifying the constants with the class name by making use of the static import facility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use of static import to avoid qualifying constants | |
import static com.effectivejava.science.PhysicalConstants.*; | |
public class Test { | |
double atoms(double mols) { | |
return AVOGADROS_NUMBER * mols; | |
} | |
} |
In summary, interfaces should be used only to define types, they should not be used to export constants.
No comments:
Post a Comment