ReasonJun

Solidity : encapsulation & hiding in OOP 본문

Blockchain/Solidity

Solidity : encapsulation & hiding in OOP

ReasonJun 2023. 10. 17. 16:13
728x90

Encapsulation

Encapsulation is one of the four main principles of OOP, often referred to as the four pillars of OOP, which also include inheritance, polymorphism, and abstraction. Encapsulation involves bundling data (attributes or properties) and methods (functions or procedures) that operate on that data into a single unit, known as a class. This class acts as a blueprint for creating objects, instances of the class. The key aspects of encapsulation are:

  • Data Hiding: Encapsulation restricts direct access to an object's internal data (attributes) from outside the class. It encapsulates the data by making it private or protected. This ensures that the data is accessed and modified through well-defined methods (getters and setters), allowing the class to maintain control over its state.
  • Information Hiding: Encapsulation also hides the implementation details of a class from the external world. Clients of the class only need to know how to use its public interface (public methods), not how those methods are implemented internally. This abstraction of the implementation details simplifies maintenance, reduces the risk of unintended side effects, and enhances security.
  • Access Control: Access modifiers like "public," "private," and "protected" in OOP languages enable you to control the visibility and access to class members. Public members are accessible from anywhere, private members are only accessible within the class, and protected members are accessible within the class and its subclasses.

 

Data hiding

Data hiding is a specific aspect of encapsulation that focuses on concealing the internal data or state of an object within a class. This is achieved by making the attributes private or protected, preventing direct access or modification from external code. Data hiding offers several benefits:

  • Encapsulated data can be validated and controlled through methods, ensuring that it remains in a consistent and valid state.
  • It allows for better maintainability, as you can change the internal representation of the data without affecting the external code that uses the class.
  • Security and error prevention are enhanced since external code cannot corrupt or misuse the object's data.
  • It facilitates versioning and backwards compatibility, as you can update the internal representation while maintaining the same external interface.

In summary, encapsulation is a fundamental OOP concept that combines data and methods into a single unit (class), and it encompasses both data hiding (restricting access to internal data) and information hiding (concealing implementation details). These principles lead to more organized, maintainable, and secure code in OOP.

728x90
Comments