views:

76

answers:

2

I have a C# class library behind a WCF service. The library contains ClassA which is declared as static. This static class has a method MethodA which accepts a string and uses LINQ to query the database for a translation of the string which it then sends back through the webservice to the client.

My question is whether using a static class and static method in this situation is bad design. Should the class and method be non-static so that each client gets their own instance of the class for performance, contention, or other reasons? Thanks.

+2  A: 

I'm personally more forgiving towards static methods and classes than some people might be, so I'd say it depends. Is the static method reentrant and thread safe? Then it might be okay. Otherwise it would probably scale badly.

One problem I see is the data context. With a static method, you probably don't have fine grained control over the life span of the database connection? An alternative might be to make it a non-static class and method, and initializing it in a static constructor of the WCF service. That way you can more easily modify the behavior later if need be.

Actually, static constructors in WCF services are bad, if they have any chance of failing, like the database being AWOL for a second. The point was that it would allow more fine grained control in the service itself.

Thorarin
Thanks for your response.
CletusLoomis
+1  A: 

I agree with what Thorarin has already answered. I usually don't see any harm in static classes, esp. when it contains only static methods that do something and return a result without ever touching any static fields or properties. However, as soon as there are modifications of any of those, that could mean trouble. (Search e.g. for any discussion on Singletons and concurrency here on SO.)

Performance-wise, calling a static method should theoretically be slightly faster than calling a non-static method (although for all practical purposes this will probably never make any significant difference), since the runtime doesn't have to pass a this/Me pointer and because with static methods, there'll definitely be no overhead resulting from virtual method calls.

stakx
Good point on the properties :) If you need to keep any state (apart from initialization perhaps), that's going to be a problem for someone sooner or later.
Thorarin
Thanks for your response.
CletusLoomis