Effective Java 2nd Edition: Difference between revisions
From My Limbic Wiki
| (15 intermediate revisions by the same user not shown) | |||
| Line 20: | Line 20: | ||
* '''Item 1 – Consider static factory methods instead of constructors''' Static factories have names, can return cached instances or subtypes, and allow better control of object creation. | * '''Item 1 – Consider static factory methods instead of constructors''' Static factories have names, can return cached instances or subtypes, and allow better control of object creation. | ||
< | <pre class="code java">Boolean.valueOf(true);</pre> | ||
* '''Item 2 – Consider a builder when faced with many constructor parameters''' Use the '''Builder pattern''' to replace telescoping constructors: | * '''Item 2 – Consider a builder when faced with many constructor parameters''' Use the '''Builder pattern''' to replace telescoping constructors: | ||
< | <pre class="code java"> | ||
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) | |||
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build(); | .calories(100).sodium(35).carbohydrate(27).build(); | ||
</pre> | |||
* '''Item 3 – Enforce the Singleton property with a private constructor or an enum''' Prefer <code>enum</code> singletons: | * '''Item 3 – Enforce the Singleton property with a private constructor or an enum''' Prefer <code>enum</code> singletons: | ||
< | <pre class="code java">public enum Elvis { INSTANCE; }</pre> | ||
* '''Item 5 – Prefer dependency injection to hardwiring resources''' Pass dependencies through constructors instead of creating them internally. | * '''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 <code>try-with-resources</code> or <code>Cleaner</code> instead. | * '''Item 7 – Avoid finalizers''' They’re unreliable and slow. Use <code>try-with-resources</code> or <code>Cleaner</code> instead. | ||
| Line 45: | Line 44: | ||
* '''Item 10 – Always override <code>toString</code>''' Make it human-readable and useful for debugging/logging. | * '''Item 10 – Always override <code>toString</code>''' Make it human-readable and useful for debugging/logging. | ||
* '''Item 12 – Consider implementing <code>Comparable</code>''' Enables sorting and ordering: | * '''Item 12 – Consider implementing <code>Comparable</code>''' Enables sorting and ordering: | ||
< | <pre class="code java"> | ||
public int compareTo(PhoneNumber pn) { | |||
int result = Short.compare(areaCode, pn.areaCode); | |||
if (result == 0) | |||
result = Short.compare(prefix, pn.prefix); | |||
if (result == 0) | |||
result = Short.compare(lineNum, pn.lineNum); | |||
return result; | |||
} | |||
</pre> | |||
---- | ---- | ||
| Line 76: | Line 67: | ||
** Don’t leak <code>this</code> in constructors | ** Don’t leak <code>this</code> in constructors | ||
* '''Item 16 – Favor composition over inheritance''' Inheritance creates tight coupling. Prefer wrapping a member instead: | * '''Item 16 – Favor composition over inheritance''' Inheritance creates tight coupling. Prefer wrapping a member instead: | ||
<pre class="code java">class InstrumentedSet<E> extends ForwardingSet<E> { ... }</pre> | |||
* '''Item 17 – Design and document for inheritance, or prohibit it''' If you don’t want subclasses, mark the class <code>final</code>. | * '''Item 17 – Design and document for inheritance, or prohibit it''' If you don’t want subclasses, mark the class <code>final</code>. | ||
* '''Item 18 – Prefer interfaces to abstract classes''' A class can implement multiple interfaces but extend only one class. | * '''Item 18 – Prefer interfaces to abstract classes''' A class can implement multiple interfaces but extend only one class. | ||
| Line 88: | Line 80: | ||
* '''Item 25 – Prefer lists to arrays''' Arrays are covariant and unsafe, while generics are type-safe. | * '''Item 25 – Prefer lists to arrays''' Arrays are covariant and unsafe, while generics are type-safe. | ||
* '''Item 26 – Favor generic methods''' | * '''Item 26 – Favor generic methods''' | ||
<pre class="code java">public static <E> Set<E> union(Set<E> s1, Set<E> s2) { ... }</pre> | |||
* '''Item 27 – Use bounded wildcards to increase API flexibility''' | * '''Item 27 – Use bounded wildcards to increase API flexibility''' | ||
** <code><? extends T></code> for producers | ** <code><? extends T></code> for producers | ||
| Line 108: | Line 101: | ||
* '''Item 38 – Check parameters for validity''' Validate arguments early, e.g.: | * '''Item 38 – Check parameters for validity''' Validate arguments early, e.g.: | ||
<pre class="code java">>this.range = Objects.requireNonNull(range);</pre> | |||
* '''Item 39 – Make defensive copies when needed''' Prevent callers from modifying internal state: | * '''Item 39 – Make defensive copies when needed''' Prevent callers from modifying internal state: | ||
<pre class="code java">this.start = new Date(start.getTime());</pre> | |||
* '''Item 40 – Design method signatures carefully''' Keep APIs small, intuitive, and consistent. | * '''Item 40 – Design method signatures carefully''' Keep APIs small, intuitive, and consistent. | ||
| Line 119: | Line 114: | ||
* '''Item 45 – Minimize the scope of local variables''' Declare variables as close as possible to their first use. | * '''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 46 – Prefer for-each loops to traditional for loops''' Cleaner and safer: | ||
<nowiki><code>for (Element e : elements) { ... }</code></nowiki> | |||
* '''Item 48 – Avoid float and double if exact answers are required''' Use <code>BigDecimal</code> for monetary values. | * '''Item 48 – Avoid float and double if exact answers are required''' Use <code>BigDecimal</code> for monetary values. | ||
* '''Item 49 – Prefer primitives to boxed primitives''' Avoid <code>Integer</code>, <code>Long</code>, etc., unless necessary. | * '''Item 49 – Prefer primitives to boxed primitives''' Avoid <code>Integer</code>, <code>Long</code>, etc., unless necessary. | ||
| Line 141: | Line 137: | ||
* '''Item 66 – Synchronize access to shared mutable data''' Use synchronization or concurrency utilities to prevent race conditions. | * '''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 68 – Prefer executors and tasks to threads''' Use: | ||
<pre class="code java">ExecutorService executor = Executors.newFixedThreadPool(10);</pre> | |||
* '''Item 69 – Prefer concurrency utilities to wait and notify''' Use <code>BlockingQueue</code>, <code>CountDownLatch</code>, etc., instead of manual thread coordination. | * '''Item 69 – Prefer concurrency utilities to wait and notify''' Use <code>BlockingQueue</code>, <code>CountDownLatch</code>, etc., instead of manual thread coordination. | ||
Latest revision as of 22:31, 5 October 2025
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 constructors Static factories have names, can return cached instances or subtypes, and allow better control of object creation.
Boolean.valueOf(true);
- Item 2 – Consider a builder when faced with many constructor parameters Use the Builder pattern to replace telescoping constructors:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8)
.calories(100).sodium(35).carbohydrate(27).build();
- Item 3 – Enforce the Singleton property with a private constructor or an enum Prefer
enumsingletons:
public enum Elvis { INSTANCE; }
- 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-resourcesorCleanerinstead.
2. Methods Common to All Objects
Key points
- Item 8 – Obey the general contract when overriding
equalsMust be reflexive, symmetric, transitive, consistent, and return false fornull. - Item 9 – Always override
hashCodewhen you overrideequalsOtherwise, your objects won’t work properly inHashMap,HashSet, etc. - Item 10 – Always override
toStringMake it human-readable and useful for debugging/logging. - Item 12 – Consider implementing
ComparableEnables sorting and ordering:
public int compareTo(PhoneNumber pn) {
int result = Short.compare(areaCode, pn.areaCode);
if (result == 0)
result = Short.compare(prefix, pn.prefix);
if (result == 0)
result = Short.compare(lineNum, pn.lineNum);
return result;
}
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
thisin constructors
- Item 16 – Favor composition over inheritance Inheritance creates tight coupling. Prefer wrapping a member instead:
class InstrumentedSet<E> extends ForwardingSet<E> { ... }
- 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 ofList. - Item 25 – Prefer lists to arrays Arrays are covariant and unsafe, while generics are type-safe.
- Item 26 – Favor generic methods
public static <E> Set<E> union(Set<E> s1, Set<E> s2) { ... }
- 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:
@Testinstead of naming test methodstestSomething().
6. Methods
Key points
- Item 38 – Check parameters for validity Validate arguments early, e.g.:
>this.range = Objects.requireNonNull(range);
- Item 39 – Make defensive copies when needed Prevent callers from modifying internal state:
this.start = new Date(start.getTime());
- 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:
<code>for (Element e : elements) { ... }</code>
- Item 48 – Avoid float and double if exact answers are required Use
BigDecimalfor 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
Stringfor 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:
ExecutorService executor = Executors.newFixedThreadPool(10);
- 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.