Search code examples
c#.netarchitecturesolid-principles

How to design two similar (but not completely) classes?


Here is the situation. We have two printers from different providers (manufacturers). We want top-level code to stay unaware of details about providers and just use uniform API. So I have started to extract an interface.

public interface IPrinterProvider {
    bool Connect(string comPort);
    bool IsConnected();
}

OK. Now, I realized that one printer requires Password property, but the other does not. So, what should I do?

And once more. As I understand, I'll have one or a couple of interfaces and a couple of implementors. But how will a caller work? Should I create a separate class, which might not implement any interfaces? For instance:

public class CommonPrinterProvider {
    private IPrinterProvider printerProvider;
    public CommonPrinterProvider(IPrinterProvider printerProvider) {
        this.printerProvider= printerProvider;
    }
}

So, two questions in total.


Solution

  • I would encapsulate printer "settings" (or, more accurately, "connection settings") into another class and have that in the interface. Somewhat like this:

    public class PrinterSettings {
        public string Password { get; set; }
        public int Port { get; set; }
        /* .. others .. */
    }
    
    public interface IPrinterProvider {
        void Initialize(PrinterSettings settings);
        bool Connect(string comPort);
        bool IsConnected();
    }
    

    Then each implementation can deal with the settings in whatever way they see fit.