Search⌘ K

Property Functions

Explore property functions in D programming to understand how to maintain data consistency within structs by defining calculated properties. This lesson demonstrates using functions as properties to compute values like area dynamically and also shows how to support assignment operations that modify underlying struct fields logically without breaking invariants.

Property functions that return values

As a simple example, let’s consider a rectangle struct that consists of two members:

D
struct Rectangle {
double width;
double height;
}
void main() {}

Let’s assume that a third property of this type becomes a requirement, which should provide the area of the rectangle:

auto garden = Rectangle(10, 20);
writeln(garden.area);

One way of achieving that requirement is to define a third member:

D
struct Rectangle {
double width;
double height;
double area;
}
void main() {}

A flaw in that design is that the object may easily become inconsistent. Although rectangles must always have the invariant of “width * height == area,” this consistency may be ...