I am having a design issue regarding .NET properties.
interface IX
{
Guid Id { get; }
bool IsInvalidated { get; }
void Invalidate();
}
Problem:
This interface has two read-only properties, Id
and IsInvalidated
. The fact that they are read-only, however, is by itself no guarantee that their values will remain constant.
Let's say that it were my intention to make it very clear that…
Id
represents a constant value (which may therefore be safely cached), whileIsInvalidated
might change its value during the lifetime of anIX
object (and so shouldn't be cached).
How could I modify interface IX
to make that contract sufficiently explicit?
My own three attempts at a solution:
The interface is already well-designed. The presence of a method called
Invalidate()
allows a programmer to infer that the value of the similarly-named propertyIsInvalidated
might be affected by it.This argument holds only in cases where the method and property are similarly named.
Augment this interface with an event
IsInvalidatedChanged
:bool IsInvalidated { get; } event EventHandler IsInvalidatedChanged;
The presence of a
…Changed
event forIsInvalidated
states that this property may change its value, and the absence of a similar event forId
is a promise that that property will not change its value.I like this solution, but it's a lot of additional stuff that may not get used at all.
Replace the property
IsInvalidated
with a methodIsInvalidated()
:bool IsInvalidated();
This might be too subtle a change. It's supposed to be a hint that a value is computed freshly each time — which wouldn't be necessary if it was a constant. The MSDN topic "Choosing Between Properties and Methods" has this to say about it:
Do use a method, rather than a property, in the following situations. […] The operation returns a different result each time it is called, even if the parameters do not change.
What kind of answers do I expect?
I am most interested in entirely different solutions to the problem, along with an explanation how they beat my above attempts.
If my attempts are logically flawed or have significant disadvantages not yet mentioned, such that only one solution (or none) remains, I would like to hear about where I went wrong.
If the flaws are minor, and more than one solution remains after taking it into consideration, please comment.
At the very least, I would like some feedback on which is your preferred solution, and for what reason(s).