Properties
harakim
harakim at gmail.com
Sun Jul 21 03:04:42 UTC 2024
On Saturday, 20 July 2024 at 17:05:57 UTC, IchorDev wrote:
> The way I see `@property` used (and the way I use it also) is
> to mark functions as being intended to be used like fields:
> `a.x`, `a.x = b`. This suggestion would break that meaning
> without functionally improving properties at all. I think the
> way properties work at the moment is better than the suggested
> functionality.
I like seeing all the DIP ideas. They make me think.
On the subject at hand, I see a lot more property use at work
than in D since I rarely see anyone else's D code. In my
experience there are a few valid ways to use properties:
1. To auto-convert data that was serialized in another form. For
example, you load an object from a database or file and it is a
string, but you want to convert it to a date and time or
expiration date or something custom. This is a valid use case. It
can also be used for setting. It has no backing data.
2. To validate data before saving it to the object to enforce
invariants. This has backing data and is valid as long as it
doesn't mutate it.
3. Computing a property. For example, having an Age property but
the backing data/field is a birthdate. This is get only and does
not have any data of its own.
4. Providing a different access modifier for setters public
DateTime BirthDate { get; private set; }. I question if this is
worth a language feature.
Problematic or pointless ways to use properties:
1. Using it exactly like a field. public string Name { get; set;
}. There is no point to this. It makes reflection slightly easier
but otherwise it is a waste of a language feature.
2. Modifying the data on input. Even something like stripping
whitepsace can often cause me to have to look through the code
(b/c it is not matching on equals, for example) to figure out
what is actually happening. That is not intuitive.
If I were to move in a direction it would be to support the valid
cases and not support the invalid cases. D allows you to create
getters without setters and it's a little more verbose than C#
but honestly that is probably preferable after my experience with
C# and the ubiquitous { get; set; }. Especially since you could
make a standard to mark getters with pure or something like that.
More information about the dip.ideas
mailing list