views:

151

answers:

3

Hi,

For the last year or so I have followed the idea that if a method could be static, to make it static, as this can have a performance benefit, and I have therefore ended up with some static classes in my applications.

I have since learned the performance benefit is not often large enough to be worthwhile, and also the distinction that methods that can be made static, perhaps shouldn't be from a design point of view, if they are more specific to the object, rather than the type - related question

As an example I have recently made a FileRepository class, that implements the repository pattern for our own File class (for example import files). This class is not static, and a repository object must first be created before it can be accessed.

My issue with this, is all my old static calls, are now 2 lines (unless I can re-use the object in local scope). The repository object (as yet) has no state, as it uses database access via a thread static variable.

My question is, what are people's opinions on having a thread static Current property on the class, where the get accessor initialises the object on the first call? As I understand it, this would still avoid the pitfalls of static classes, such as not being able to implement generic functionality via interfaces, but still offer the ease of single line calls to the repository object?

Just trying to adjust my practices and mindset for the better.

+5  A: 

Statics tend to hurt testability.

In particular, you'll find it relatively hard to test anything which uses the repository. Instead of creating a new repository on each call, it should be part of the state of anything which requires it. Use dependency injection to supply the repository, which implements an appropriate interface. You can then test anything which uses the repository by mocking it out.

Of course, this is an idealist solution which may not be the pragmatic solution for your case - but it's a generally object-oriented one.

You could have the "current" repository and still be reasonably testable, but it still requires static state which is generally frowned upon. It's a slight code smell, but it would at least be better than the static methods.

Jon Skeet
Wow! This is the first time I'm seeing **1 sec** difference between two answers.
Mehrdad Afshari
+1  A: 

One benefit of not using static stuff and always hold direct references to dependencies is the ability to mock and unit test objects easily. You'll lose this ability if you directly reference your static class or current property.

Mehrdad Afshari
A: 

You need to explain what sort of performance degradation your talking about. Are we talking micro seconds?

Quite often, application performance can be improved by running a profiler and to find the offending code. Have a look at ANTS profiler as an example.

All to often I find database access the culprit 70% of the time.

Sir Psycho