Solved

Shared Functions

Posted on 2012-12-27
4
165 Views
Last Modified: 2013-01-10
Is there a rule of thumb when to use and when not  to use "Shared"  in a Class. I can see the benefit from this sample. However, should I use shared all the time so that I don't have to cretae a new object each time?

http://www.sitecrafting.com/blog/aspnet-20-tips-shared-functions/
0
Comment
Question by:VBdotnet2005
  • 2
4 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
ID: 38724552
The topic of shared (static) vs. instance is hotly debated. I think in the general sense, you use shared members whenever there is no need to maintain the state of something.

The classic example is the Math class. When you perform the absolute value of a number, is there any reason to maintain the state of the operation? In other words, if I say:

Math.Abs(-3)

...should the Math class store the -3 for future use? Mathematically speaking, no. Every time I run the Abs function for a given input, I should expect to get the same result. And there is no guarantee that I will be executing the Abs function with an argument of -3 in the future, so it doesn't make much sense to keep it.

The flip side...

I have an Airport class, and it is used to route planes into and out of the Airport. Would it not make sense to keep track of the number of planes I have already parked at the terminal, how many planes are taxied to the runway, and how many planes I have in a holding pattern waiting to land? In this case, there is much state that needs to be maintained. Shared members in this scenario probably wouldn't make much sense.


In the crude sense, shared members can be convenient in that you don't have to create and maintain instances of some class (which you may need to later dispose of). In the end, it comes down to the design of your system and your personal preferences.
0
 
LVL 8

Expert Comment

by:Crashman
ID: 38724560
in my opinion,use it for utilities methods, you cannot contains shared variables, because you are not in control about his value in some time.
0
 
LVL 8

Assisted Solution

by:Crashman
Crashman earned 250 total points
ID: 38724568
here, a most certain approach


I wrote my thoughts of static classes in an earlier thread:
http://stackoverflow.com/questions/205689/class-with-single-method-best-approach#206481

I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.

Polymorphism

Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.

Interface woes

Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by passing delegates instead of interfaces.

Testing

This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.

Fosters blobs

As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.

Parameter creep

To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyways.

Demanding consumers to create an instance of classes for no reason

One of the most common arguments is, why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();

Only a Sith deals in absolutes

Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.

Standards, standards, standards!

Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.


http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 38725460
As a rule of thumb and in plain worlds I would say:
- A shared or static member (either field, property or method) doesn't require to use contextual information from an specific class instance.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Web site error 3 41
Adding Existing Item to vb.net Project causes Errors 4 32
What Does This C# Code Block Do? 5 31
Convert datetime to time string 10 21
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question