Junior — Middle
Why is it important to use encapsulation in object-oriented systems?
sobes.tech AI
Answer from AI
Encapsulation is a principle of object-oriented programming that allows hiding the internal details of an object and providing access to data only through specific methods. This is important because:
- It protects data from incorrect or unintended external modification.
- It simplifies support and modification of code, as internal changes do not affect the external interface.
- It increases readability and structure of the code.
- It allows controlling access and data validation.
An example in Node.js using classes and private fields:
class User {
#password; // private field
constructor(name, password) {
this.name = name;
this.#password = password;
}
checkPassword(input) {
return input === this.#password;
}
}
const user = new User('Alice', 'secret');
console.log(user.name); // Alice
console.log(user.#password); // Error: private field
console.log(user.checkPassword('secret')); // true
Thus, encapsulation helps create more reliable and maintainable systems.