views:

72

answers:

1

For applications of any size, what are the drawbacks of using a Context.Current pattern? (i.e. "Current" is a shared/static property of a "Context" class that instantiates itself the first time it's used)

Any advantage of using this pattern over just shared / static classes/methods?

I'm asking in the context of .NET, although I guess it could apply in a variety of languages.

+3  A: 

This is a kind of singleton pattern, usually representing thread-local storage. A well-known example in the .NET world is the HttpContext.

The most common issue is testability. Certainly not impossible, but the pattern does encourage a usage model which is not compatible with TDD, so using it requires extra vigilance. In ASP.NET MVC, we see a much improved pattern by which the context object itself is passed through each layer as an input parameter, rather than relying on the singleton storage to access that object.

Another way to look at it is that it does not play well with other, arguably much more useful, OO patterns such as dependency injection. Most would argue you get a lot more mileage from being able to use DI than from having a convenient singleton shortcut to your current state.

As with any singleton or global state, it also introduces a set of problems with multi-threading and concurrency. There are well-established patterns for mitigating these, but obviously any time you use a pattern which requires "mitigation" you expose yourself to a lot of risk which would otherwise not be an issue.

There are sometimes appropriate places for singletons, but they are very few and far between. The decision to store state in a singleton should be very carefully made by an experienced team. An inexperienced team should avoid them to be on the safe side.

Rex M