Windows Runtime API design principles around read-write properties: Idempotence and self-assignment

Wait 5 sec.

Objects in the Windows Runtime can have properties, and those properties could be read-only or read-write. For read-write properties, there are a few general principles. Today we're going to look at this one:Setting a property to its current value is legal and has no effect.¹For example:// C#o.Color = o.Color;// C++/WinRTo.Color(o.Color());We are setting a property's value to the value it already has.Now, this may look like a pointless thing to write on its own, but it could fall out of other code.// C#o.Color = EnsureSufficientContrast(o.Color, m_backgroundColor);// C++/WinRTo.Color(EnsureSufficientContrast(o.Color(), m_backgroundColor);The hypothetical Ensure­Sufficient­Contrast function returns a foreground color that provides sufficient contrast against a background color. It's possible that the existing foreground color already provides sufficient contrast, in which case the original color is returned unaltered.This principle seems obvious, but it comes with corollaries.Corollary: Setting a property twice to the same value has no effect.Setting the property multiple times is the same as setting it once.I remember many years ago I was looking at a customer program, and they had a property called Print. Setting it to True caused a document to print. I don't mean that it resulted in a printout happening when you submitted the document. I mean it printed the document at the moment you set the Print property. If you wanted to print two copies, you would dodocument.Print = True ' Print itdocument.Print = True ' Print it againThis was definitely a violation of the idempotence principle. As well as a violation of other principles like "What were you thinking?"Next time, I'll look another simple corollary to the idempotence principle that people often are tempted to violate.¹ By "no effect" here, I mean no functional effect. Clearly the code runs more slowly because you're performing a redundant operation, and there might be follow-on calculations that occur when the property is set. But the point is that the correctness of the program is not affected by the redundant write to the property.