Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
David Karlsson4,180 Points
Why use protocol for the VendingMachine instead of Class?
Hey, I'm confused as to why we'd make the VendingMachine a protocol and not a class. All the different types of VendingMachines will be VendingMachines as well and the only difference is the VendingSelection, wouldn't it make more sense if VendingMachine was a class and the different types were sub classes?
Ivan Penchev13,832 Points
This question (which you can google as Class vs Instance) is one that plagues OOP devs for years and for years to come :=) The short answer is: because is the better way to accommodate potential future changes.
I wonder if the example I should provide, should be directly on this project. Nah...lets make it a bit more abstract so that I spark some curiosity and some thinking.
Lets take a downloading example.
You has a Base class FileDownloadModel and have 3 subclasses AudioFileDownloadModel, VideoFileDownloadModel, ImageDownloadModel.
You have a DownloadManager that takes input as FileDownloadModel and uses its urlToDownload Property of model to download the file.
Later down the line you are told that, there is one more model coming but its like UserDownloadModel which subclass from User.
See now it becomes difficult to handle the such scenario where you will have to change a lot of code to incorporate downloading methods.
How protocol oriented programming will help you here:
Create a protocol named DownloadingFileProtocol and add methods that you need for downloading file. eg. urlToDownload, pathToSave, extension etc.
Implement the same protocol in FileDownloadModel and UserDownloadModel. See the benefit that you don't have to change a lot of code in UserDownloadModel. You will just implement the methods from DownloadingFileProtocol.
See if again a new entity comes down the line, you will not change any code just implement the protocol methods.
And now your DownloadManager can take input as DownloadingFileProtocol instead of a specific model and now you can make any model as Downloadable.