JS interview in 2 minutes / Encapsulation (OOP)
Question:
What is Encapsulation?
Quick answer:
Encapsulation can be used in any meaning of any of these terms or both:
- Mechanism used to restrict access to some of an object's properties.
- Mechanism that allows data access only via related methods or functions (setters and getters).
Longer answer:
Basically, the first definition is only about creating private properties.
Btw there are no private properties in JavaScript but looks like there is a proposal. In Typescript private properties are present.
Another definition is just a way to say that access to every property is implemented via getters and setters.
class User { private salary = 0; setSalary(salary: number) { this.salary = salary } getSalary() { return this.salary }}let user = new User()console.log(user.getSalary()) // 0user.setSalary(10)console.log(user.getSalary()) // 10
Real-life applications:
This getters & setters pattern was always confusing to me and felt like a total redundancy, haven't changed my opinion still.
There is a list with a bunch of good reasons why getters & setters can be useful, but I can't say that I actually had an issue with any of the described topics.
// Here goes super opinionated section
Feels like the whole industry is moving to not deeply using OOP and preferring immutable objects and pure functions over data mutations, so this topic maybe just a tribute to old times
// end of super opinionated section
If you know a good example of beneficial use of getters and setters, please share it in the comments
Resources:
wiki/encapsulation
tutorialspoint/java/encapsulation
Other posts:
- JS interview in 2 minutes / Polymorphism (OOP)
- JS interview in 2 minutes / Inheritance in OOP
- JS interview in 2 minutes / Object-Oriented Programming (OOP)
Btw, I will post more fun stuff here and on Twitter. Let's be friends
Original Link: https://dev.to/kozlovzxc/js-interview-in-2-minutes-encapsulation-oop-2ico
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To