Effective java notes

  • Item 38: check parameters for validity

    Most methods and constructors have some restrictions on what values may be passed into their parameters. For example, index values must be non-negative and object values must be non-null.
    You should enforce them with checks at beginning of the method body.

    Notes:

    1. Once an error occur, throw the exception as early as possible
    2. For public methods, use Javadoc @throws tag to document the exception. (IlliegalArgumentException, IndexOutofBoundsException, or NullPointerException)
    3. For un exported methods, use assert for validity checks, e.g., assert a != null;. Enable assert by command -ea (or -enableassertions) to the java interpreter.
    4. It is particular important to check the validity of parameters that are not used by a method but are stored away for later use. (It’s quite hard to debug if there is an error in this case)
    5. Design API to be as general as it is practical to make them.
  • Item 39: Make defensive copies when needed

    Notes:

    1. Never trust a user input data
  • Item 40: Design method signatures carefully

    Notes:

    1. Avoid too many functions in a class | interface
    2. Avoid long parameter list (larger than 4)
    3. For parameter types, use interfaces instead of classes
    4. For control parameters, prefer two-element enum types to boolean
  • Item 41: Use overloading judiciously

    Notes:

    1. overload: polymorphism in compile time; override: polymorphism in run time
    2. Avoid using different types of a parameter to design overloading methods
    3. Never export two overloading with the same number of parameters
  • Item 42: Use varargs judiciously

  • Item 43: Return empty arrays or collections, not nulls

    Notes:

    1. It’s arguable that a null return is preferable to an empty array in case of mitigating system expense.
    2. The right way to return an array of a collection

        // The right way to return an array of a collection
      private final List<Cheese> cheeseInStock = ...;
      private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
      public Cheese[] getCheese() {
      return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
      }
    3. The right way to return a copy of a collection

      // The right way to return a copy of a collection
      public List<Cheese> getCheeseList() {
      if (cheesesInStock.isEmpty())
      return Collections.emptyList(); // Always returns same list
      else
      return new ArrayList<Cheese>(cheesesInStock);
      }
  • Item 44: Write doc comments for all exposed API elements

    Notes:

    1. @param, @return, @throws
    2. @throws starts with if statement
    3. @{code} and@{literal}
    4. Document enum and annotation types