Junior
Why is encapsulation needed in programming?
sobes.tech AI
Answer from AI
Encapsulation is needed to hide the internal implementation of an object from the outside world and to provide access to its data only through a defined interface (methods).
Advantages:
- Reduced complexity: Using an object boils down to calling its public methods, without requiring knowledge of its internal structure.
- Manageability: Changing the internal implementation of an object does not affect the code that uses it, provided the external interface remains unchanged.
- Data security: Prevents direct uncontrolled modification of the object's state from outside, ensuring its integrity.
- Flexibility: Allows easy replacement of the object's internal implementation with another, more efficient one, without changing client code.
Example in JavaScript (using private fields):
class Counter {
#count = 0; // Private field
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
const myCounter = new Counter();
myCounter.increment();
console.log(myCounter.getCount()); // Outputs 1
// console.log(myCounter.#count); // Will cause an error, as #count is private