January 3rd, 2006

On the abuse of properties

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

(void)o.p;
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.]

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.