I have an class named FileCreator which is used to write many strings to a stream. Basically, to achieve its job, the FileCreator needs two objects: a StreamWriter and the actual strings that will be written to the stream. So far so good.
Now, on a architectural level, I'm wondering what would be the proper way to pass the Streamwriter to the FileCreator. I see three solutions, but all have their downsides:
In the FileCreator class, create a method named let's say Write that would receive the StreamWriter and the string to write. For example, in c# it would be:
public void Write(StreamWriter sw, string stringToWrite);
Issue with this solution: This solution would work, but the StreamWriter needs to be passed every time a string needs to be written. It feels weird, and not OO at all.
The FileCreate should have 2 methods:
public void SetWriter(StreamWriter writer); public void Write(string stringToWrite);
This solution would work, but it brings temporal coupling. Basically, the caller must know that SetWriter must be called one before the calls to Write. And let's say the Write method is called before setting the Writer... throw a custom exception indicating something like 'Writer should be set'? ... feels weird.
Make the FileCreator constructor have the StreamWriter as a parameter to prevent the issue raised in the previous solution.
public FileCreator (StreamWriter writer); public void Write(string stringToWrite);
While this may work well in some situations, in our system, it would not. This is because we are doing unit tests with dependancy injection. In our situation, the StreamWriter cannot be injected because some of its properties like EOL characters, Encoding and FilePath are determined by business rules at run time in other methods.
So in your opinion, what would be the appropriate solution? Maybe there are other techniques that could be applied? Hope my question in clear!