Intern
What is the essence of encapsulation?
sobes.tech AI
Answer from AI
The essence of encapsulation is the bundling of data and methods that operate on that data into a single entity (object) and hiding the internal implementation from the outside world.
Main principles:
- Data hiding: Access to an object's data is only through its public interface (methods). Direct access to internal fields can be restricted (for example, using keywords like
privateor#). - Providing an interface: The object provides a set of public methods through which external parts of the program can interact with it and modify its state.
- Protection from incorrect usage: Hiding implementation details allows controlling how the object's data is changed, preventing incorrect states.
Example in JavaScript:
class User {
#name; // Private field
constructor(name) {
this.#name = name;
}
getName() { // Public method to get data
return this.#name;
}
setName(newName) { // Public method to change data with validation (optional)
if (newName && typeof newName === 'string') {
this.#name = newName;
} else {
console.error('Invalid name');
}
}
}
const user = new User('Ivan');
console.log(user.getName()); // Access via public method
// console.log(user.#name); // Error, no direct access to private field
user.setName('Peter');
console.log(user.getName());
user.setName(123); // Will cause an error inside the method
Advantages:
- Modularity: Code becomes more organized and easier to maintain.
- Flexibility: The internal implementation of the object can be changed without affecting the external code that uses it, provided the public interface remains the same.
- Security: Prevents unauthorized or incorrect access to data.
- Reusability: Objects with a clearly defined interface are easier to use in different parts of an application or in other projects.