Effective Java
Creating and Destroying Objects
Static Factory Method instead of Constructors
Names improve readability
Different methods for different use cases
Only one constructor with same signature
Caching possible
Can return subtype
Java8 allows static methods
Allow service provider frameworks
e.g. JDBC, DriverManager.getConnection
Also great for test fixtures
of(), from()...
Builder for many Constructor Parameters
Static factories and constructors don't scale for large number of optional parameters
Telescoping constructor as an anti pattern
Devs might confuse parameters with same type (compiler doesn't care(
JavaBeans pattern
Empty contructor + setters
Creates partially inconsistent objects during creation
Builder pattern instead
Create builder, set values (fluent), call build()
E.g. as static member class
Builder for Class Hierarchies
Implement using a generic type with a recursive type paramter
Builder<T extends Builder<T>>
Use parent builder type in subclasses
Beware: Problematic for other JVM languages (Kotlin, Scale)
See Testcontainers GenericContianer
Builder for Class Hierarchies
Implement using a generic type with a recursive type paramter
Builder<T extends Builder<T>>
Use parent builder type in subclasses
Beware: Problematic for other JVM languages (Kotlin, Scale)
See Testcontainers GenericContianer
Singleton
Public static field
Easy to implement, but strong coupling
Static factory method
Singleton becomes implementation detail
Use factory or runtime checking for testability?
Single-element enum
Simple to implement
Strong guarantees
Can find improve the existing codebase? Examples?
Made with Slides.com