3 ms·
I think it comes from a too-literal understanding of design patterns. E.g., for the factory pattern the common practice (outside of some well designed APIs e.g.
by strlen 16y ago
I think it comes from a too-literal understanding of design patterns. E.g., for the factory pattern the common practice (outside of some well designed APIs e.g., google collections) the common practice is:
public class Image {
public Image(byte[] data) {
// create the image from byte array
}
}
public class ImageFactory {
public Image createImage(File file) throws IOException {
// read data then create an image
}
}
vs.
public Image {
// the same constructor, but then ...
public static Image open(File file) throws IOException {
// Do the same thing as factory would do
}
}
What's the advantage of the first approach, provided there's no per-instance state (and thus reason not to just use a static factory method) within the ImageFactory class?
- prodigal_erik 16y agoAt runtime you can provide a different implementation of ImageFactory. For example, a unit test can define MockImageFactory which ignores the filesystem and just returns a canned Image object. If code everywhere calls the static Image.open method, there is no way to redefine it short of editing the source or the bytecode.
- strlen 16y agoGood answer. That actually makes sense with the Image example, but OTOH there's still cases where a separate factory class is used where a static method would work.
- rbanffy 16y agoI think that's one of the reasons. It's so nice to be able to provide a different GadgetFactory during tests or at different moments that some developers decide it would be cool to have the possibility to provide different factory implementations for every class, just in case they need it afterwards.
- barrkel 16y agoTo which the counter-argument is YAGNI (the different implementations). There are other ways to do the equivalent of mocking, though the interface / factory approach is popular at the cost of doubling the number of identifiers in play and probably having a geometric effect on complexity.