Effective Java 2nd Edition

From My Limbic Wiki
Revision as of 22:16, 5 October 2025 by Fukakai (talk | contribs)

Book: Effective java 2nd Edition

10 commandments:

  • Use static factories and builders wisely.
  • Make classes immutable when possible.
  • Favor composition over inheritance.
  • Use Generics properly β€” never raw types.
  • Prefer Enums over constant values.
  • Validate arguments and maintain invariants.
  • Minimize variable scope and visibility.
  • Use exceptions only for exceptional cases.
  • Leverage modern concurrency utilities.
  • Write readable, safe, and self-documenting code.

1. Creating and Destroying Objects

Key points

  • Item 1 – Consider static factory methods instead of constructorsStatic factories have names, can return cached instances or subtypes, and allow better control of object creation.

<code>Boolean.valueOf(true);</code>

  • Item 2 – Consider a builder when faced with many constructor parametersUse the Builder pattern to replace telescoping constructors:

<code>

NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();

</code>

  • Item 3 – Enforce the Singleton property with a private constructor or an enum
  • Prefer enum singletons:
  • Item 5 – Prefer dependency injection to hardwiring resources
  • Pass dependencies through constructors instead of creating them internally.
  • Item 7 – Avoid finalizers
  • They’re unreliable and slow. Use try-with-resources or Cleaner instead.

🧩 2. Methods Common to All Objects

βœ… Key points

  • Item 8 – Obey the general contract when overriding equals Must be reflexive, symmetric, transitive, consistent, and return false for null.
  • Item 9 – Always override hashCode when you override equals Otherwise, your objects won’t work properly in HashMap, HashSet, etc.
  • Item 10 – Always override toString Make it human-readable and useful for debugging/logging.
  • Item 12 – Consider implementing Comparable Enables sorting and ordering:

🧱 3. Classes and Interfaces

βœ… Key points

  • Item 13 – Minimize the accessibility of classes and members Encapsulation is key. Hide as much as possible (private, package-private).
  • Item 15 – Favor immutability Immutable objects are thread-safe, simple, and reliable. Rules:
    • No setters
    • All fields final
    • Don’t leak this in constructors
  • Item 16 – Favor composition over inheritance Inheritance creates tight coupling. Prefer wrapping a member instead:
  • Item 17 – Design and document for inheritance, or prohibit it If you don’t want subclasses, mark the class final.
  • Item 18 – Prefer interfaces to abstract classes A class can implement multiple interfaces but extend only one class.

🧠 4. Generics

βœ… Key points

  • Item 23 – Don’t use raw types Always use parameterized types: List<String> instead of List.
  • Item 25 – Prefer lists to arrays Arrays are covariant and unsafe, while generics are type-safe.
  • Item 26 – Favor generic methods
  • Item 27 – Use bounded wildcards to increase API flexibility
    • <? extends T> for producers
    • <? super T> for consumers β†’ PECS rule: Producer Extends, Consumer Super

πŸš€ 5. Enums and Annotations

βœ… Key points

  • Item 30 – Use enums instead of int constants Safer, more powerful, can have fields and methods.
  • Item 35 – Prefer annotations to naming patterns Example: @Test instead of naming test methods testSomething().

🧰 6. Methods

βœ… Key points

  • Item 38 – Check parameters for validity Validate arguments early, e.g.:
  • Item 39 – Make defensive copies when needed Prevent callers from modifying internal state:
  • Item 40 – Design method signatures carefully Keep APIs small, intuitive, and consistent.

πŸ” 7. General Programming

βœ… Key points

  • Item 45 – Minimize the scope of local variables Declare variables as close as possible to their first use.
  • Item 46 – Prefer for-each loops to traditional for loops Cleaner and safer:
  • Item 48 – Avoid float and double if exact answers are required Use BigDecimal for monetary values.
  • Item 49 – Prefer primitives to boxed primitives Avoid Integer, Long, etc., unless necessary.
  • Item 50 – Avoid strings where other types are more appropriate Don’t use String for enums, IDs, or complex data.

πŸ’₯ 8. Exceptions

βœ… Key points

  • Item 58 – Use exceptions only for exceptional conditions Don’t use exceptions for control flow.
  • Item 59 – Favor the use of standard exceptions Use built-ins like IllegalArgumentException, NullPointerException, etc.
  • Item 63 – Include failure-capture information in detail messages Exception messages should help diagnose the issue.

🧡 9. Concurrency

βœ… Key points

  • Item 66 – Synchronize access to shared mutable data Use synchronization or concurrency utilities to prevent race conditions.
  • Item 68 – Prefer executors and tasks to threads Use:
  • Item 69 – Prefer concurrency utilities to wait and notify Use BlockingQueue, CountDownLatch, etc., instead of manual thread coordination.

πŸ“¦ 10. Serialization

βœ… Key points

  • Item 74 – Implement Serializable with great caution Serialization breaks encapsulation and can introduce bugs or security issues. Avoid it if possible, or mark fields transient.