No, not at the same time… 🙂
I got sent a couple of articles today from a colleague at work. One to do with the Null-Object pattern and one to do with achieving performance increases through better use of the .Net base class library.
First – the performance article. This one is an older article (Jan 2006) but is a handy one to have in the library. Having not previously read it, I was surprised by a couple of things. First of all the old String vs StringBuilder comparison. I was under the impression that it’s never better to use string over StringBuilder when concatenating strings. Apparently, that’s not quite right. The magic number of operations (with the caveat in this case of concatenating 25 character strings) seems to be around 7.
Of course, even if you’re only doing a couple of small additions you’ve got future proofing to consider. Is this likely to be wrapped in some form of recursion? Is my 1 or 2 concatenation function going to be called 55 times by a higher purpose? Is that under my control?
The conclusion I’ve come to – though it may go against the article is that it’s almost always better to use the StringBuilder. But I tend to err on the safe side…
The other article was on the Null-Object pattern. This pattern advocates the use of a class which implements all the required members of an interface – with either a default functionality or empty code block. See here or here for a more detailed description.
To me, this is really a dependent pattern. By itself I don’t see much value in it. However when coupled with a factory pattern – it becomes valuable. Why? Well part of the purpose of the null-object pattern is to remove the need for object equals null checks in code. If you can’t control the object however, the null check is still required as the caller/client could still potentially hand you a null object and therefore cause an exception (which is expensive – see above mentioned article!).
However – if you’re using a factory of some sort to supply you an object based on an interface this solves the issue of what to do if the factory doesn’t know which instance to return by giving it a default implementation. So you can then have what is basically a stub being returned to allow your code to run safely, sans null checks.
Originally, I wasn’t so keen on this. It makes the code look flaky. After a chat about it, some more coffee and a bit of perhaps not so quiet reflection (I mutter when I think) I’ve come to see the benefits of this particular beast. It makes your code more concise. There is less code for codes sake, and more action going on – and that makes me happy 😛