Simplify object creation
Have you ever found yourself in a situation where you’ve been growing your class, adding more and more constructors all with their own configuration specifics? Have you ever wished that you could take out the object creation code into a separate class and reorganize it to be more readable?
Let’s take a look at a scenario right out of the Refactoring to Patterns book. Here we have several loan constructors all hiding the real intent in the parameters they take:
Now, let’s refactor these constructors into factory methods. To do so, we take each constructor in turn and use the Replace Constructor with Factory Method refactoring choosing in the Refactor This menu Control+Shift+R.
Consequently, we can give the new factory method a name, but we can also specify a different class in which to put the factory method.
What you end up with is a factory method in the LoanFactory
class:
Doing this for all relevant constructors will yield a complete factory class. Note that if you put the factory methods in the originating class (for example, Loan
), the corresponding constructors will turn private. But since we moved these constructors into a separate factory class, the constructors remain public.