harriyott.com

Using using

Daniel Moth has been experimenting with using the "using" statement to perform common entry and exit code. The using statement calls the constructor of a class at the beginning, and Dispose() at the end. The before code (status bar and wait cursor in his example) goes in the constructor, and the after code goes in Dispose(). Clever trick.

I post this because Daniel finishes his post thinking the approach is "wrong" and asking for feedback, but doesn't seem to have comments enabled. I'll post my thoughts here instead.

I think it's quite neat, and as the original developer, there's one less thing to think about when doing something, which is always useful. The problem comes with maintainability. He mentions the problem that no memory management actually takes place, and the leap would have to be made to understand that. This would only come to light when looking at the class.

If the maintenance coder didn't look at the class, just the using statement, she would assume that there was some memory stuff going on, and wonder where the heck the status bar text was getting changed. Eventually she'd have to look at the class, and realise that the original coder was a blatant liar. "Hey punk, there's no memory management here!". From that point on, she trusts the original coder a whole lot less, and has to check more classes just to confirm that they do what they say they do.

In this (admittedly contrived) example, a better approach would be to explicitly state what the code was doing by using meaningful method names:

SetGuiWaiting();
DoTheThing();
SetGuiReady();

or

guiController.SetWaiting();
DoTheThing();
guiController.SetReady();

Now the maintainer can just read what's going on without having to visit the other code. Not quite as pleasing for the original developer, but a lot easier to maintain. Still, an interesting idea, and it's always worth experimenting with things like this.

As for a class with only a constructor and a Dispose(), I'm not bothered by that, if the abstraction requires nothing else.

[Tags: ]
4 July 2006