DEV Community

Discussion on: Explain Encapsulation and Polymorphism Like I'm Five

Collapse
 
robencom profile image
robencom • Edited

Encapsulation is related to the visibility of properties/methods. Basically, if you have a sensitive property (for example, an 'age' property that should not be lower than 18) which you do not wish to be explicitly changed, then you declare it as private and provide getters and setters in which you can make sure that your rule (age > 18) is respected.

Polymorphism means "multiple shapes". This comes handy when you have a functionality, such as sending notifications to users, that might have several forms, such as sending an email notification or an SMS notification. You must make sure that you are "programming to an interface, not to an implementation". This means that your notification sending mechanism should refer to the interface that is implemented by both of your email and SMS sending notification classes. So you are depending of the interface that has MANY forms (email and SMS), making your code both clean and flexible.