Dart Encapsulation
Encapsulation in Dart
Encapsulation is one of the core concepts of Object-Oriented Programming (OOP). It refers to the bundling of data (fields) and methods that operate on that data within a single unit, i.e., a class. It also restricts direct access to some of the object's components and only exposes a controlled interface. This helps protect the integrity of the object's state by ensuring that its fields are accessed or modified only in specific ways.
In Dart, encapsulation is achieved by:
- Private fields: Fields that are prefixed with an underscore (
_
) to make them private to the class. - Public methods (getters and setters): These methods provide controlled access to the private fields.
Benefits of Encapsulation:
- Data Hiding: Keeps the internal state of the object hidden from the outside world and only allows controlled access via methods.
- Control Over Data: You can validate or transform data before it is set or retrieved.
- Increased Security: Prevents unauthorized or unintended modification of an object's state.
Example: Encapsulation in Dart
Let’s create a Person
class that demonstrates encapsulation. The class will have a private field _age
, and we will provide public methods to get and set the age, but with validation to ensure the age is always a positive value.
Explanation:
Private fields: The
_name
and_age
fields are private to thePerson
class because they are prefixed with an underscore (_
).Getters and Setters:
- The getter methods (
name
andage
) provide read access to the private fields. - The setter methods (
name
andage
) allow controlled modification of the private fields. The setter forage
ensures that the value is non-negative, and the setter forname
ensures it’s not empty.
- The getter methods (
Encapsulation ensures that the
Person
object’s internal state is protected, and its data is only modified or accessed in a controlled way through the provided methods.
Output:
Key Points:
- The
_name
and_age
fields are encapsulated within thePerson
class. They cannot be accessed directly from outside the class. - The getter and setter methods control access to these private fields, ensuring that invalid data is not set.
- Encapsulation allows for greater flexibility in the future. For example, if you later decide to change how the
age
field works (e.g., adding additional validation), you can do so without changing the rest of your codebase, as the external code interacts only with the getter and setter methods.
Encapsulation is a powerful mechanism to control and protect data, ensuring that the internal state of objects remains consistent and valid.