Effective Java Reloaded - illyfrancis/scribble GitHub Wiki

Effective Java reloaded

Forward

  • Grammar
  • Vocabulary
  • Idiom

List

47, 8, 9, 10, 36, 38 (re-read) 48, 39, 15, 41, 49, 45, 43

15. Minimize mutability

Recipe
  • Don't provide mutators
  • Ensure the class can't be extended (final and private constructors)
  • Make all fields final
  • Make all fields private
  • Ensure exclusive access to any mutable components (defensive by copying)
Advantage
  • Simple
  • Inherently thread-safe
  • Can be shared freely
  • Can share internals

=> persistent data structure

Cons
  • Require separate object for each distinct value

49. Prefer primitive types to boxed primitives

Primitives vs. Reference type
  • Values vs. Values + Identities
  • Only funcation values vs. one nonfunctional value (has null)
  • time / space efficiency vs. < time /space efficiency

When to use boxed primitives

  • when API requires it, generics, collection elements etc

41. Use overloading judiciously

  • Never export two overloadings with same number of parameters

8. Obey the general contract when overriding equals

Know when not to override
  • Inherently unique instances (e.g. thread)
  • 'logical equality' unimportant (e.g. random)
  • superclass does the right thing (e.g. collections)
  • equals will never be invoked (e.g. private class)
  • singletons (also enums)
Contract
  • reflexivity
  • symmetry
  • transitivity
  • consistency
  • non-nullity
You cannot extend an instantiable class and add a value component while preserving the equals contract! => use composition instead of inheritance
Use Guava for equals
public class Person {
  final String name, nickname;
  final Movie favMovie;

  @Override public boolean equals(Object object) {
    if (object == this)
      return true;
    if (object instanceof Person) {
      Person that = (Person) Object;
      return Objects.equal(this.name, that.name)
        && Objects.equal(this.nickname, that.nickname)
        && Objects.equal(this.favMovie, that.faveMovie);
    }
    return false;
  }
  ...
}
On Java 7, Objects is available (No need for Guava)

9. hashcode

General contract
  • Calling hashCode on same object, same JVM , must return the same integer
  • if two objects are equal must return same integer on each object
How to implement
  • Want uniform distribution
  • refer to book for detail
  • or use Guava return Objects.hashCode(areaCode, prefix, lineNumber);