re: Explain Encapsulation and Polymorphism Like I'm Five VIEW POST


Object-Oriented Programming

Encapsulation (the good parts) basically means don't share your private data. That way no one can depend on it, and you can change it (structurally or literally mutating a value) without breaking anyone using your object. 99% of what you should expose on an object is "behavior" aka methods. That way the user of the object focuses on what behavior they want to utilize, not the details of the data. Exceptions being, of course, DTOs which are objects used purely for data purposes. These are used a lot at the edge of systems, because bits going over the wire or being rendered to a monitor, are only data anyway.

Polymorphism is simply substituting one object for another. For example, a car can have a key or push-button start. They work inherently differently, but you could substitute one for the other. Note that since you mentioned Python -- a dynamic language -- you probably don't have to worry about polymorphism too much in practice. It is understood that a variable could be any object. If I call .foo() on the object then I am obviously expecting that method to be there no matter which specific type of object I was given. Static typed languages require extra syntax to handle polymorphism, which could be one of the reasons it is extra emphasized.

Functional Programming

Encapsulation is not so common in FP, since you are encouraged to separate data and functions (into types and modules respectively). Types are primarily used as a means of communication between functions, so they usually don't make sense as private things. And you also don't have to worry about the data you communicated out to another function being changed out from under you, due to immutability. So there's not much need to make data private or encapsulate it behind an object with methods. The FP languages I use do allow for private data, but I rarely bother.

FP does make extensive use of polymorphism, especially for core types like List and the functions on them. So you can make a list of Widget or a list of FooBar. List provides the same functionality no matter which type it is containing. So you can also use the filter function on a list of Widgets or a list of FooBar. In addition to collections, FP typically has some other polymorphic types like Result and Maybe to represent data which can be in an either/or state.

Code of Conduct Report abuse