Book Summary: Effective Java 3rd Edition
Effective Java Second Edition
Creating and Destroying Objects
Item 1: Consider static factory methods instead of constructors
-
- unlike ctors, they have names and don’t have restriction of same parameters
-
- not required to create a new object each time (caching immutables, Flyway pattern, instance-controlling)
-
- return any sub class, interface-based frameworks, compact api
-
- return sub class based on parameters
-
- implementing classes do not need to exist when this class was written (service loader pattern)
-
- you can’t subclass classes without public/protected constructors (favor composition over inheritence)
-
- not highlighted as constructors in javadoc
Item 2: Consider a builder when faced with many constructor parameters
- traditionally used “telescoping constructors” (problematic with same parameter types) or java bean pattern (empty constructors + setters) (cannot be immutable, or via freeze state)
-
- simulates names optional parameters
-
- can respect class hierarchies
-
- cleaner business class when having many parameters, with proper validation in builder setter methods
-
- more verbose than telescoping constructors
Item 3: Enforce the singleton property with a private constructor or an enum type
- singleton as field makes the api clearer
- singleton as getInstance() allows for later modification
- singleton as single enum type is prefered due to clean api, 100% single + serialization for free
Item 4: Enforce noninstantiability with a private constructor
- abstract class does not help due to subclassing
- throw AssertionError if protection against reflection is needed
Item 5: Prefer dependency injection
- through constructor or factories instead of singletons or final class with static field+methods
- testability is improved
Item 6: Avoid creating unnecessary objects
- String literals get cache by jvm
- string.matches -> use final static Pattern
- prefer primitives to boxed primitives
- watch out for unintentional autoboxing
Item 7: Eliminate obsolete object references
- whenever a class manages its own memory, be alert for memory leaks
- nulling out objects should be an exception
- listeners and callsbacks can lead to memory leaks if not unregisterer
Item 8: Do not use finalizers
- when tey are run is unpredictable, maybe won’t even run
- exceptions in finalizers are swallowed
- runned on low-prio thread
- Cleaners replace finalizers for Java9+, static instance which gets a runnable, managed by a jvm threads, unpredictable
- should only be used when resource freeing is not trusted to user or as a falseback net