I’ve got this piece of legacy code which I’m trying to refactor at the moment:
public class FileManger
{
private IFileReader _fileReader;
private IFileWriter _fileWriter;
public enum Mode { Read = 1, Write = 2 };
public void Open( Mode mode)
{
if (mode == Mode.Read)
{
_fileReader = new FileReader();
}
else if (mode == Mode.Write)
{
_fileWriter = new FileWriter();
}
}
}
I need to be able to replace this piece of code with a factory method and assign the returned to a common filed.
so.. I’m trying to make it look like:
public class FileManger
{
private IFileHandler _fileHandler;
public enum Mode { Read = 1, Write = 2 };
public void Open(string fileName, Mode mode)
{
_fileHandler = Factory.CreateFileHandler(mode);
}
}
The problem I have is the two original interfaces IFileReader and IFileWriter, though they are quite closer in shape to each other, they have two completely different methods string ReadLine(); and void WriteLine(string line); for which I could not find a common abstration.
Basically my refactoring goal is to make the IFileReader and IFileWriter interfaces look the same and use a common interface instead of two.
currently these interfaces look like this:
public interface IFileReader : IDisposable
{
void OpenFileStream(string fileName);
void Close();
string ReadLine();
}
and
public interface IFileWriter : IDisposable
{
void OpenFileStream(string fileName);
void Close();
void WriteLine(string line);
}
could someone give me some suggestions on how I could go around achieving this?
Please let me know if you need any further clarifications, if I made it unclear to understand.
I can’t really see why you would like to use a common interface for such different operations, but assuming you have good reasons for that, I guess you could do something like this, where
linewould be read or written, depending on file mode: