[Proposal]: [Cacheable] attribute for methods and getters #3982
Replies: 4 comments
-
This seems like a perfect use case for source generators. I don't think I'm convinced that there needs to be a specific language feature for this. |
Beta Was this translation helpful? Give feedback.
-
I see. With the implementation of records in C#9, isn't it that the demand for small immutable objects and lazy initizialization will rise? The feature doesn't seem to affect the rest of the language... |
Beta Was this translation helpful? Give feedback.
-
And should I close the proposal as you reject it? |
Beta Was this translation helpful? Give feedback.
-
I'll convert this to a discussion. I didn't outright reject it: while I'm not super interested in this proposal, perhaps other members of the LDT will be. Personally, caching is too specific of an issue to add a major feature around. I'd rather see something like delegated properties (a la Kotlin), which is a more general solution that might be able to deal with this. However, that still likely wouldn't play nice with |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
FEATURE_NAME
Summary
Implement an attribute that would cache the value returned by methods (in particular, properties' getters) after the first call.
Motivation
The main use for it is lazy initialization. There are quite a few ways to write it, to be precise, via
Lazy<T>
, nullable field and check, and conditional weak table.The first two require another field to be declared, which might be bad as
record
, so that if we need correct equality comparison, we need to override CompareTo when have such fieldsCacheable would either
In either way, this attribute would clean the code a lot. Compare
and
Adding it would help to follow the patterns of programming so that we do not have to care about storing the cache somewhere.
Detailed design
Although I thought of this name for the attribute from Java, since it is slightly different, there might be a better name for it, for example,
[Cached]
, or[ToCache]
.Drawbacks
It takes the developer yet a bit further from full understaning how their cached methods work making their job implicit.
Alternatives
Alternatives have been mentioned in motivation. Overall, it cleans the code a lot and might help avoiding equality overriding for records.
Unresolved questions
Name and the implementation itself. I think, the best way is to create a private secret backing field, but then it would be necessary to change the auto-generated equality operator so that this field is ignored.
Beta Was this translation helpful? Give feedback.
All reactions