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.
We'll cover the following...
Property functions that return values
As a simple example, let’s consider a rectangle struct that consists of two members:
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:
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 ...