C
C#8mo ago
Nectar

Program to an Interface means in Head First Design Patterns book

in the book it says that "the declared type of the variables should be a supertype, usually an abstract class or interface, so that the objects assigned to those variables can be of any concrete implementation of the supertype, which means the class declaring them doesn't have to know about the actual object types!", and when they implemented it it was exactly the same as what I understood: https://hastebin.com/share/mavecaruwo.csharp (the original code is written in java and some things I reduced to simplify the code), but in the next page the illustration questions the decision of the author "Wait a second, didn't you say we should NOT program to an implementation? But what are we doing in that constructor? We're making a new instance of a concrete Quack implementation class!", after which the author tries to explain his decision (the explanation is in the picture), but the explanation makes me ask, what's wrong with the code? doesn't the code fulfill "program to interface/supertype"? Isn't the meaning of program to interface just like IAnimal animal = new Dog() instead of Dog dog = new Dog() (where dog implements IAnimal)?
thank you!
Hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
No description
2 Replies
Tvde1
Tvde18mo ago
The author seems to mostly mean, if you use IAnimal animal = new Dog(), you have one spot to update if you want to switch to a different animal so if you use IAnimal through lots of parts of the code, that'll be easier for later unfortunately textbook examples of inheritance always make zero sense, with IQuackBehavior and IAnimal, etc
Nectar
NectarOP8mo ago
thanks for answering. I think it's another meaning of program to interface, but it doesn't answer why the illustration questions the author's decision that clearly the author implements program to interface.
Want results from more Discord servers?
Add your server