Effective Java 2nd Edition: Difference between revisions
From My Limbic Wiki
No edit summary |
No edit summary |
||
| Line 39: | Line 39: | ||
---- | ---- | ||
== | == 2. Methods Common to All Objects == | ||
=== | === Key points === | ||
* '''Item 8 β Obey the general contract when overriding <code>equals</code>'''Β Must be reflexive, symmetric, transitive, consistent, and return false for <code>null</code>. | * '''Item 8 β Obey the general contract when overriding <code>equals</code>'''Β Must be reflexive, symmetric, transitive, consistent, and return false for <code>null</code>. | ||
| Line 50: | Line 50: | ||
---- | ---- | ||
== | == 3. Classes and Interfaces == | ||
=== | === Key points === | ||
* '''Item 13 β Minimize the accessibility of classes and members'''Β Encapsulation is key. Hide as much as possible (<code>private</code>, <code>package-private</code>). | * '''Item 13 β Minimize the accessibility of classes and members'''Β Encapsulation is key. Hide as much as possible (<code>private</code>, <code>package-private</code>). | ||
| Line 65: | Line 65: | ||
---- | ---- | ||
== | == 4. Generics == | ||
=== | === Key points === | ||
* '''Item 23 β Donβt use raw types'''Β Always use parameterized types: <code>List<String></code> instead of <code>List</code>. | * '''Item 23 β Donβt use raw types'''Β Always use parameterized types: <code>List<String></code> instead of <code>List</code>. | ||
| Line 78: | Line 78: | ||
---- | ---- | ||
== | == 5. Enums and Annotations == | ||
=== | === Key points === | ||
* '''Item 30 β Use enums instead of int constants'''Β Safer, more powerful, can have fields and methods. | * '''Item 30 β Use enums instead of int constants'''Β Safer, more powerful, can have fields and methods. | ||
| Line 87: | Line 87: | ||
---- | ---- | ||
== | == 6. Methods == | ||
=== | === Key points === | ||
* '''Item 38 β Check parameters for validity'''Β Validate arguments early, e.g.: | * '''Item 38 β Check parameters for validity'''Β Validate arguments early, e.g.: | ||
| Line 97: | Line 97: | ||
---- | ---- | ||
== | == 7. General Programming == | ||
=== | === Key points === | ||
* '''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. | ||
| Line 109: | Line 109: | ||
---- | ---- | ||
== | == 8. Exceptions == | ||
=== | === Key points === | ||
* '''Item 58 β Use exceptions only for exceptional conditions'''Β Donβt use exceptions for control flow. | * '''Item 58 β Use exceptions only for exceptional conditions'''Β Donβt use exceptions for control flow. | ||
| Line 119: | Line 119: | ||
---- | ---- | ||
== | == 9. Concurrency == | ||
=== | === Key points === | ||
* '''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. | ||
| Line 129: | Line 129: | ||
---- | ---- | ||
== | == 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 <code>transient</code>. | * '''Item 74 β Implement Serializable with great caution'''Β Serialization breaks encapsulation and can introduce bugs or security issues.Β Avoid it if possible, or mark fields <code>transient</code>. | ||
Revision as of 22:17, 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 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
enumsingletons: - 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:
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:
- 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
- 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.:
- 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
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:
- 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.