Search code examples
oopinheritanceinterfaceabstraction

Interface with multiple implementations and confusion about parameters


I have created the following interface:

public interface IReader
{
    string Read();
}

One implementation of it, is an XmlFileReader that encapsulates the logic to read xml files from disk based on a path stored in the config file.

Another implementation of it, is a FileReader that would read a file from disk based on the path specified as a parameter.

Now the confusion is that, the XMLFileReader doesn't require any parameter in the Read() method whereas the FileReader does. Should I add an optional parameter to IReader.Read() method, so that in the case of FileReader I can provide the file path using the parameter and in the case of XMLFileReader the parameter would not be used?

Another option could be to create a separate interface with a Read() method that takes the parameter.

What would be a good design for this scenario?


Solution

  • The canonical solution is to put the parameters in the constructors of the concrete classes.

    That said, I don't think your design is sound: what does return the XmlReader.Read method? Keep in mind that the user of an interface should ignore the concrete class it's using. So, after the call to IReader.Read(), it shouldn't do different elaborations on the string according to the type of the file. Is this your case?

    It seems to me that the variation you want to capture is not the "Read the file" part, but the "How do I get the right file to read". In this case, an interface with a "Read" method is useless.

    In any case: IReader, XmlFileReader and FileReader are really bad names for your classes. You should avoid -er suffix: see this good article. And keep in mind that inheritance should model a IS-A relation.