Search⌘ K
AI Features

Use of Properties

Explore how to use properties in D programming to encapsulate member variables, ensuring controlled access and modification. Understand why properties improve code maintenance by restricting direct variable access and fostering better design in object-oriented structures.

Properties are not absolutely necessary

We saw in the previous lesson how Rectangle can be used as if it has a third member variable. However, regular member functions could also be used instead of properties:

D
import std.stdio;
import std.math;
struct Rectangle {
double width;
double height;
double area() const {
return width * height;
}
void setArea(double newArea) {
auto scale = sqrt(newArea / area);
width *= scale;
height *= scale;
}
}
void main() {
auto garden = Rectangle(10, 20);
writeln("The area of the garden: ", garden.area());
garden.setArea(50);
writefln("New state: %s x %s = %s",
garden.width, garden.height, garden.area());
}

Further, as we already know, these two functions could even have ...