'Private class method or interface? [closed]
I'm working on an app which uses the Factory pattern to create new objects. In the Factory Class I've added a new Private method called SendApprovalEmail()
and I am calling this from within the Process()
method.
There are other Factory classes which will have their own implementation of SendApprovalEmail()
. Therefore should I make an interface (containing a SendApprovalEmail()
method) which these factory classes can inherit from? Or is it an acceptable approach to have a private method on each factory class which is just called from their Process()
method?
Looking around the app, they tend to use interfaces when extending the factory classes. Unsure what the pros and cons of this are?
Solution 1:[1]
I would not put this in an interface. This would be a good situation to use a protected virtual function — if this method is intrinsic to your factory design (i.e. should be included in all factory classes) rather than just part of this particular factory implementation.
The reason for my suggestion is that you say the function is private. You wouldn’t usually put private methods in an interface.
If it really is private then that would suggest that it is not going to be defined in a similar way for other factories I.e. it is just part of this particular factory’s implementation.
However you other comments sound like it is going to also be a necessary part of the design for other factories. In that case you would make it virtual (or abstract) protected so that it can be redefined in other factory classes.
Solution 2:[2]
A private member makes no sense as part of an interface. An interface is there to define a set of methods, a role, an object must always implement. Private methods, on the other hand, are implementation details, not intended for public consumption.
Solution 3:[3]
I agree with @sjb-sjb. Depending on what you want to accomplish an interface or abstract method would be way more appropriate. These two options would enforce implementation per class inheritance. An abstract method on a base class would offer far more flexibility. Yeah, but that method cannot stay private if you want to implement inheritance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sjb-sjb |
Solution 2 | Mucahit Tozal |
Solution 3 | aventer_5b |