Search code examples
interfacesolid-principlesopen-closed-principledependency-inversion

Is the Open-Closed SOLID principle the same as Coding to an Interface?


Does open-for-extension and closed-for-modification mean code-to-an-interface?

If I code to an interface so that future concrete implementations can be introduced by implementing the interface, and we create new classes without touching existing logic, does it achieve the same goal we try to address using the open-for-extension and closed-for-modification SOLID principle?


Solution

  • I would say that code-to-an-interface solves the open-close-principle (OCP) but there are other ways to code-to-an-interface.

    Code-to-an-interface could also mean to code to an abstract-class like InputStream.

    Also the use of CDI could allow beans to be closed-for-modification and open-for-extensions.

    This means that you must not use interfaces but you can in order to use OCP.

    If I code to an interface (...) does it achieve (...) SOLID principle?

    Yes, you follow the SOLID principle. But implementors of the interface might not.

    Usually the interface is separated into a method-signature and the javadoc. The method-signature specifies what you technically could do and the javadoc should specify what the implementation should do. Both ways, signature and doc are hard facts and a implementation that violates either the signature or the javadoc mostly should reported as a bug.

    So you can either use a existing interface for common requirements or a new interface for specific requirements. If you create a new interface you might think about the interface-segregation-principle what also is part of the SOLID-principle-collection.

    If you design this interface you must be open for requirements of the implementor. In example if the interface is like this:

    Date readDate(InputStream in);
    

    There might be some requirements from the implementors you could never have foreseen:

    1. You should add a IOException in the case the stream is closed.
    2. You should add a Charset-Parameter because the charset is ASCII what means the bitlength is 7 bit, not 8 bit.
    3. You should add a Timezone because Date use the timezone of the server whearat the stream sources from a different timezone.
    4. You should add Locale because the year/month/day format (UK) could be year-month-day format (GER) in a different locale.

    Theese requirements might appear after you coded-to-an-interface. I would say those requirements to the interface forces you to modify your code-to-an-interface that are closed. You could say, yes this is a modification that violates against closed-for-modifications. But none of theese "requirements to the interface" really need to modify the behaviour of your code-to-an-interface.