Good Constructors Flashcards
What are the two problems with common constructors?
- Too many (optional) parameters
2. Magic numbers
What are the four most common constructor techniques?
- Builder
- Static Factory Method
- Telescoping
- Java Bean
How is the builder pattern implemented?
Public static inner class contains mandatory and. optional variables. Builder constructor with only mandatory parameters.
How do you use a builder constructor?
A = new A.Builder(100,10)
.y(1)
.y(2)
.build();
What are static methods?
An instance of the class needs to be created in order to call them.
How do static factory methods work as a constructor?
Static methods return different instances of the class
How are static factory methods implemented and used?
public static A newInstance(){ return new A(); }
A a = A.create();
What are telescoping constructors?
Various constructors of different sizes. Smaller ones call the next bigger one.
What is reflection in java?
A programm can examine a class definition and use it.
How are JavaBeans used as a constructor?
- Create empty object with constructor
2. set parameters with setters
When would you use a builder and when a static factory method?
Builder: > 5 Parameters
SFM: < 5 Parameters