use_interface_references_to_collections

Use interface references to Collections

Return to Java terms or Java best practices

Use Java interface references to Java Collections - http://www.javapractices.com/topic/TopicAction.do?Id=26

In general, references to Java objects should be as generic as possible. The user of such a reference will be protected from possible changes to the underlying implementation Java class | class. The ripple effects of such a change are limited to the single line of code which creates the object, and will not propagate any further.

In the case of Java collections | collections, this means habitually referring to collection objects using Java List | List, Java Map | Map, Java Set | Set, Java Queue | Queue, and Java Deque | Deque interface references.

Note as well that all of these except Map can be referred to using the even more generic Java Collection | 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 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 getQuarkSummary() {
   LinkedHashMap 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);
   

use_interface_references_to_collections.txt · Last modified: 2025/02/01 06:23 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki