Minimize ripple effects
In the case of collections, this means habitually referring to collection objects using
List
,
Map
,
Set
,
Queue
,
and Deque
interface references.
Note as well that all of these except Map
can be referred to using the even more generic
Collection
.
Example
import java.util.*; public class Nucleus { public static void main (String... args) { Nucleus lithium = new Nucleus (3,4); //note the generic Map reference is used here, not LinkedHashMap Map<String, Integer> quarks = lithium.getQuarkSummary(); log("Number of up quarks in lithium nucleus: " + quarks.get("Up")); log("Number of down quarks in lithium nucleus: " + quarks.get("Down")); } public Nucleus(int numProtons, int numNeutrons) { this.numProtons = numProtons; this.numNeutrons = numNeutrons; } /** Note this get method is final. */ public final int getNumProtons() { return numProtons; } /** Note this get method is final. */ public final int getNumNeutrons() { return numNeutrons; } /** * This method returns a Map which summarizes how many quarks of each * flavour are in the nucleus. * * @return a generic Map reference, instead of a LinkedHashMap; the * user will be protected from the detail of what implementation of Map * has been selected here. */ public final Map<String, Integer> getQuarkSummary() { LinkedHashMap<String, Integer> result = new LinkedHashMap<>(); int numUp = numProtons * UP_QUARKS_PER_PROTON + numNeutrons * UP_QUARKS_PER_NEUTRON ; int numDown = numProtons * DOWN_QUARKS_PER_PROTON + numNeutrons * DOWN_QUARKS_PER_NEUTRON ; //this makes use of auto-boxing of ints into Integers: result.put("Up", numUp); result.put("Down", numDown); return result; } //PRIVATE private final int numProtons; private final int numNeutrons; private static final int UP_QUARKS_PER_PROTON = 2; private static final int DOWN_QUARKS_PER_PROTON = 1; private static final int UP_QUARKS_PER_NEUTRON = 1; private static final int DOWN_QUARKS_PER_NEUTRON = 2; private static void log(String aMessage){ System.out.println(aMessage); } }