I figured that since I have manager to build up a respectable readership here, I might as well try to make this a little more interactive, while also providing some useful information to you all.
I was in the middle of refactoring an entire class library this morning when the solution to a few of my problems came in the form of changing a Shared method to a Singleton method, and vice versa. The question then hit me, “Is there something I don’t know about the tradeoffs of using each?” I set out to research this a bit, reminding myself of some things I have forgotten over time. (Warning, I am only looking at this from the ASP.Net side of the house.)
For any newbies, or non-programmers reading this… The surface difference between the two types of methods are that a Singleton method requires an instantiation of it’s class, while a Shared (or Static in C#) method does not. This results in the difference of code such as:
' Using Singleton Methods
Dim ctlCustomer As New CustomerController
Dim intCustomerId As Integer = ctlCustomer.GetCustomerIdByName('John Doe')
' Using Shared Methods
Dim intCustomerId As Integer = CustomerController.GetCustomerIdByName('John Doe')
At it’s core, Shared Methods are great for Function or Utility Libraries, and API Libraries. However, you run into the limitations of not being able to properly inherit the function and override it. You also have differing limits in terms of the number of allowable arguments to be passed, but I find that limit too high already. Then there is also the potential to create methods that are not thread-safe, if they access or manage any state information. What’s not thread safe? Well, that would be when you access things like cache, viewstate, and so on.
In my opinion, there are some distinct scenarios where Shared methods are bad. For example: DAL (data access), Cache, and Email Notification and classes. All of these examples have the inherent need to access objects that would throw an exception, should two calls come in at the same time. Even worse, the DAL also runs the risk of overloading your connection pool to your database server. As a result, other methods that would not ordinarily timeout, will. When that happens, you don’t always get a clear message, pointing you to the true problem that I have described here.
When we think of Singleton Methods, there is an immediate concern of using more memory when we instantiate an entirely new instance of a class. There are plenty of people who (right or wrong) do not trust the Garbage Collector in .Net. Then there is also the school of thought that less code is better. If I can do something with one line of code, it’s faster, and better for the overall project, right? Maybe…
Here are a few resources I dug up on the topic through a simple search that may help you make up your own mind:
I think that’s a pretty decent introduction. What are your thoughts and experiences in using both types of methods?