14.07.2013 Views

Contents - Cultural View

Contents - Cultural View

Contents - Cultural View

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Constant interface 101<br />

}<br />

public static final double PLANCK_CONSTANT = 6.62606896e-34;<br />

This still leaves the original intent of the pattern mostly un-addressed (i.e. there is no syntax for accessing the<br />

constants unqualified). However, since Java 5, consider using static import [2] to achieve the same goal:<br />

import static Constants.PLANCK_CONSTANT;<br />

import static Constants.PI;<br />

public class Calculations {<br />

}<br />

public double getReducedPlanckConstant() {<br />

}<br />

return PLANCK_CONSTANT / (2 * PI);<br />

To varying degrees, the issues listed above have now been addressed:<br />

1. Because static members can be imported specifically, the class namespace need not be polluted with all members<br />

of the constants interface.<br />

2. Run-time and compile-time semantics are more closely aligned when using static imports instead of constants<br />

interfaces.<br />

3. The compiled code has one less binary compatibility constraint (that "class Calculations implements Constants").<br />

4. Because static imports apply only to the current file (and not the whole class hierarchy) it is easier to discover<br />

where each static member is declared.<br />

5. There is less need to declare variables of the constants interface type, and it is potentially clearer that no concrete<br />

instances actually exist.<br />

Note however, the changes do nothing to improve the cohesion of the Constants class, so static imports should not be<br />

considered to be a panacea.<br />

References<br />

[1] Bloch, Joshua, Effective Java, 2nd Edition, p. 98<br />

[2] Sun Microsystems, Inc. (2004). "Static Import" (http:/ / java. sun. com/ j2se/ 1. 5. 0/ docs/ guide/ language/ static-import. html).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!