On the abuse of properties

Raymond Chen

One thing that I see occasionally is the abuse of property syntax. IDispatch and CLR objects (and C++ objects if you want to avail yourself of a Microsoft-specific extension) support “properties”, which syntactically look like fields but internally are treated as a pair of methods (“get” and “put”). An important principle is that given an object o and a property p, the lines

o.p = o.p;

should be effectively nops. (Mind you, they might be really inefficient nops.)

My favorite (or perhaps most hated) example of violating this principle is an object I saw many years ago that had a “print” property, which if set to true, caused the object to send itself to the printer. If you did

o.print = true;
o.print = true;

then two copies of the object were printed.

Property syntax mimics field syntax for a reason: Properties should behave like fields.

(Plenty more guidance on properties can be found in the .NET Framework Property Usage Guidelines.)

[While Raymond was on vacation, the autopilot stopped working due to a power outage. This entry has been backdated.]


Discussion is closed.

Feedback usabilla icon