Re: "Program to an interface" - When to break a design pattern
On 5/10/2011 4:01 PM, Arved Sandstrom wrote:
....
I agree that _declaring_ the return type as LinkedHashMap does not
achieve that; the ironclad knowledge that it _is_ LinkedHashMap does,
even if it's declared as Map. But in some cases (see above) there is no
harm, and arguably some utility, in making the explicit declaration.
That's the point I've been trying to make. Evidently I'm running into
the "program to an interface at all costs" principle.
....
I think some of the trouble might lie in the ambiguity, in a Java
context, of the sentence "Program to an interface.".
Meaning 1: Users of some module (in the widest sense) should depend only
on what is declared and specified about the module, not on direct
knowledge of how it is currently implemented.
Meaning 2: Java programs should depend only in Java interface types to
represent what is declared and specified about a module for the use of
its callers.
I am very strongly in favor of meaning 1 of "Program to an interface.".
Everything any user of a module needs to know about it should be
declared and/or specified as part of its interface (in the general
sense), and using code should depend only on what is declared and
specified.
Failure to follow this principle can lead to fragile code in which a
change to the implementation of one module that does not change any part
of its declaration or specification breaks something else. At the worst,
nobody dares change anything.
I like Java interface types as a way of abstracting out interfaces
between modules, where appropriate, but I do not think "Program to an
interface" should be considered anywhere near as absolute a principle in
meaning 2 as in meaning 1.
Patricia