I'm employing TDD quite a bit these days and really enjoying myself - everything seems to flow better and be naturally better constructed and organized. However, while writing a bit of IO code, utilizing
System.IO.Streams, and I was wondering - when is it ever worth not using a factory? Because in
Streams case, it certainly seems better to not use a factory.
Generally, for more complex types that I have defined, such as a class that controls the authentication of something and interfaces with a database, you would probably use a dependency injection container and have this resolved at runtime without ever needing to actually create one.
However, in some circumstances, when you need to create a lot of these instances, you would create a Factory to construct that type - such as:
Foo(Bar bar, Foobar foobar, Fuzz fuzz)
Here, because you don't want to expose how to directly create this object to the clients that need it, you expose a Factory that will create them and inject that into the client instead. This has the benefit of allowing you to replace the factory at any time you want with something else and is generally used for creating instances of types which have derived types.
void Create(Bar, Foobar, Fuzz)
However, back to my
Stream point - would it even be worth creating a Factory for a decorator around a Stream? For example, in my project I have
BinaryDataStream, which reads my data from a Streeam. The BinaryData is in a custom format, and takes a Stream argument in it's constructor. Using
new seems to violate everything I know that I've learned since I started using TDD, because I am giving the dependent in which it needs to know explicitly about how to get it's collaborator However a factory seems overkill.
EDIT: I think I need to clarify. I don't mean avoiding new() all the time, as obviously it has it's use in tying up dependencies and the like. however, I meant in the following situation (copy-pasta from comments):
What I meant was that I have been told it is intrinsically evil to use the new() operator to a collaborator from inside the type that uses the collaborator, and that it is better to either a) pass an injected type or b) pass a factory (if you need to create an unknown number of those types). By using new() inside the collaborator you tie how to create that object and where to create it directly to the thing that requires it, and that it is better to inject a preconfigured instance into the constructor if you need one instance of it, or inject a factory into the constructor if you need to create multiple/undetermined number of instances