views:

14

answers:

1

A familiar problem using VisualStudio is the mysterious calling of property getters. If these have side effects (the most common being of the form if (foo == null) foo = new foo(); return foo; ), then the fact that the debugger Locals and Watch windows call the properties - without even hitting any break points - can lead to unexpected effects when debugging.

There is a simple solution to this: just tag the property with the attribute

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]

So how can I find getters which may have side effects in a large code base?

NDepend is the tool of choice for this kind of thing: using its CQL language I can find all the properties which, for example, directly change the state of their containing instance:

         SELECT METHODS FROM ASSEMBLIES "FOO" 
         WHERE IsPropertyGetter AND ChangesObjectState 

This only finds those getters which change a field directly: how can I find ones which change it indirectly, e.g. by calling an Initialize() method?

+1  A: 

Joel, indeed, CQL doesn't let write for now a query that would check indirect calls to verify 'deep' immutability. This will be possible in the next major version of NDepend in 2011.

Also, often properties getters return an object computed just-in-time (or lazy computed) that is computed the first time the getter is called. Nevertheless, we are considering adding the 2 following rules:


// Instance Property Getter should be immutable
WARN IF Count > 0 IN SELECT METHODS WHERE
IsPropertyGetter AND
!IsStatic AND
ChangesObjectState
// This rule might be violated in the case of object computed just-in-time
// when the property getter is accessed the first time.


// Static Property Getter should be immutable
WARN IF Count > 0 IN SELECT METHODS WHERE
IsPropertyGetter AND
IsStatic AND
ChangesTypeState
// This rule might be violated in the case of object computed just-in-time
// when the property getter is accessed the first time.

Patrick Smacchia - NDepend dev
Thanks Patrick. Incidentally, is it possible to use CQL to find whether a method is potentially used via an interface?
Joel in Gö