I'm creating a set of classes to represent various data in a legacy database. Instead of using exceptions inside constructors to signal error conditions I've decided to employ factory methods to create my various objects. However, I'm trying to figure out how best to reuse some of these factories when inheriting from those classes. I'm looking for a conceptual explanation (ie: best practices state that you should do ...) not so much an actual code example (although code examples are always welcome).
For example, let's say I have a class called User with a createUser factory method. I also have another class called Employee that extends the User class. How can I reuse (ie: call) all the code in the createUser method from the createEmployee method so that it populates all of the Employees fields that are inherited from the User class?
An obvious "work around" would be to change the Employee class to have a User class instead of extending it, but that doesn't mesh with normal OO principles.
You can have an additional initializeUser(User user) method, which fills all fields. createUser creates a new User and calls initializeUser with it. createEmployer creates a new Employer and calls initializeEmployer which calls initializeUser and then adds its Employer stuff.
To make it invisible to the outside user, declare both initalize methods protected so they're only visible inside the package. Another design would be to have an own factory class which holds all create and initialize methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With