I’m just all about murdering the boilerplate recently.
This aspect implements the “do not allow any public methods to be called after the object has been disposed” pattern for you, thereby trimming an arbitrarily large number of once-a-method:
if (disposed) throw new ObjectDisposedException (this.GetType().FullName) ;
out of your code and replacing it with one simple
on the class.
In the latest minor addition to the Arkane BCL, a PostSharp aspect to enable you to execute methods in multi-threaded or single-threaded COM apartments with a simple annotation. Useful for those of us who, say, want to access the clipboard but are doing so from a known-to-be-MTA application or from a library context where we don’t know the type of apartment that the application calling us uses.
Yeah, COM’s annoyingly legacy, but when you have to, you have to, right?
In further ongoing experimenting with ways I can use PostSharp to improve my code, here’s the SingletonConstraint – which doesn’t add so much value in and of itself, but rather provides the valuable service of ensuring that I’ve got my singleton idiom (a) right every time, and perhaps more importantly, (b) the same every time, which given the number of variations on the theme I’ve gone through over the years is harder than it might seem:
(Of course, this only checks the declarations, not the implementations, so I could still screw those up – but it’s a good start, and getting the declarations right makes it substantially less likely that broken implementations would compile cleanly.)
For those less obsessively self-checky than me, I could also point out that you could do much the same sort of thing to enforce your favorite coding standards on everyone in the team at assembly level… but I would never suggest such a thing. Would I?
Today’s problem has been the ever-vexing problem of external services that are too damn reliable, thus leaving one wondering how, exactly, one is supposed to test one’s error-handling code in a vaguely convenient manner if the blasted things always work. (Well, short of breaking them (inconvenient), or disconnecting from them/the Internet (if anything, more so), and – if one wants to test unreliability call-by-call, the problem that those are too blunt a hammer to use.
One could write an intercepting class or subclass to introduce the requisite unreliability for test purposes, I suppose, and ifdef it out of the release version, but that’s also an ugly solution.
Fortunately, I’ve just started using PostSharp, which makes this kind of thing gratifyingly easy. Thus:
Simply decorate the methods you’re testing failed calls to with the [CallMeMaybeAspect] attribute, optionally specifying a probability and an exception type if you don’t want InvalidOperationExceptions 10% of the time, and off you go.
(Don’t forget to remove the attribute when you’re done or #ifdef it out in the production version!)
The simple, the obvious, the almost always entirely forgotten by me: