Getters and Setters in Dart Programming
Getters and setters are an essential part of many object-oriented programming languages, including Dart. They provide a way to control access to an object’s attributes or properties, allowing you to enforce validation and apply logic when getting or setting values. In this discussion, we’ll explore the significance of getters and setters in Dart, understand how they work, and see practical examples of their use.
Understanding Getters and Setters
Getters and setters are methods that allow controlled access to an object’s attributes. They are used to read (get) or modify (set) the values of object properties, ensuring data encapsulation and providing a level of abstraction over object state.
Using Getters
Getters are methods that provide read-only access to an object’s attributes. They are defined using the get
keyword in Dart and do not take any arguments. Getters are used to retrieve the value of an attribute.
Here’s an example of a getter in Dart:
class Circle {
double _radius;
Circle(this._radius);
double get radius {
return _radius;
}
}
In this example, the Circle
class defines a getter named radius
, which provides read-only access to the private attribute _radius
.
Using Setters
Setters are methods used to modify an object’s attributes. They are defined using the set
keyword in Dart and take a single parameter, representing the new value to be set. Setters are used to enforce validation or apply logic when changing the value of an attribute.
Here’s an example of a setter in Dart:
class Temperature {
double _celsius;
Temperature(this._celsius);
set celsius(double value) {
if (value >= -273.15) {
_celsius = value;
}
}
}
In this example, the Temperature
class defines a setter named celsius
, which enforces that the new value must be greater than or equal to -273.15 (absolute zero).
Using Getters and Setters Together
Getters and setters can be used together to control access to object attributes, allowing you to both retrieve and modify values in a controlled manner.
Here’s an example of using both a getter and a setter in Dart:
class Student {
String _name;
int _age;
Student(this._name, this._age);
String get name {
return _name;
}
set age(int value) {
if (value >= 0) {
_age = value;
}
}
}
In this example, the Student
class defines a getter for the name
attribute and a setter for the age
attribute, ensuring that the age cannot be set to a negative value.
Conclusion
Getters and setters are important tools in Dart for controlling access to object attributes, enforcing validation, and applying logic during read and write operations. They play a crucial role in maintaining data integrity, encapsulation, and abstraction, ultimately leading to more robust and reliable software in Dart programming.