?
Solved

Advantages/disadvantages of Static vs Non-static methods??

Posted on 2005-03-01
9
Medium Priority
?
7,972 Views
Last Modified: 2008-02-07
Hello experts,

I'm finishing up my degree in Software Development and recently started a job as a Junior Developer.  One of the first tasks I was assigned was to create a data access tier for my part of the project.  No problem, my education covered this type of thing in relative detail.  So I go to work, get it up and running and am pretty happy with the results.  My code involves instantiating a data access object and using it's methods to interface with the database.  Pretty standard, right?  But later, I had the opportunity to look at my Lead's code for the data access tier for his part of the project.  His code looks very similar to mine except that he has used static methods to achieve the same results.

Which got me thinking...what are the advantages and disadvantages of each approach (either for this specific task or in general)?  Is one slower/faster?  Have less/more overhead?  Are there methodology or design-related reasons for using one or the other?

I realize this is kind of a general question, but I'm curious what people have to say about it.  The question is worth 500 points and I'll probably split them up among the 1-3 anwers I think contribute the most to my understanding of this issue.
0
Comment
Question by:dei1c3
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 11

Expert Comment

by:sachiek
ID: 13436679
Well, First thing I would like to share is dont limit your knowledge.

Always it is good to learn that there are more than one single way to acheive best results.

Since you have joined recently, you should be soon realizing that writing code is always been easy part of as a software developer. But controling emotions , then comparing this kind of coding all these trigger things much.

So better be patient and try to learn more.

Just my two cents... Dont mistake me if any of my comments is wrong.


Sachi
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 13436838
Static and non-static methods are used in different situations. Methods related to class instance should be non-static. Method related to the whole class and not to it's specific instance should be static.
Example: .NET Color structure. B property is non-static because it gets/sets blue component of specific Color instance:
Color c;
...
c.B = 255;

Blue is static property. It is not related to any class instance and always returns the same value:
Color c = Color.Blue;
0
 
LVL 11

Expert Comment

by:jatinderalagh
ID: 13437180
>>Methods related to class instance should be non-static. Method related to the whole class and not to it's specific instance should be static.

I will add few lines for example.

You have a class as Customer.
So in this class you can write a static method
public static Customer GetCustomer()
Which loads the data in Customer object and returns the object.


0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:WinterMuteUK
ID: 13437363
Static methods are useful for passing around the same instance of a given class between many others in the same process, without explicity passing the reference. Take for example a counter class:

public class Counter
{
  //Member Vars.
  private static int mCounter = 0;

  //Constructor.
  private Counter(){} //To ensure this class is not instanced.

  //Methods
  public static int GetCounter(){ return mCounter; }
  public static void IncCounter() { mCounter++; }
  public static void DecCounter() { mCounter--; }
}

If I have 2 classes in the same process and each one calls Counter.GetCounter(); they will get the same value, equally, incrementing or decrementing the counter by one of the classes will affect the other two classes.

public static Main()
{
  MyClass mC1 = new MyClass();
  MyClass mC2 = new MyClass();

  mC1.Print(); //Output = '0'
  mC2.Print(); //Output = '0'
  mC1.Inc();   //mC1 increments causing mC2 to see the increment as well.
  mC1.Print(); //Output = '1'
  mC2.Print(); //Output = '1'
  mC2.Dec();  //mC2 decrements causing mC1 to see the decrement as well.
  mC1.Print(); //Output = '0'
  mC2.Print(); //Output = '0'
}

public class MyClass{
  public void Print(){ Console.WriteLine(Counter.GetCounter()); }
  public void Inc(){ Counter.IncCounter(); }
  public void Dec(){ Counter.DecCounter(); }
}
   
Cheers
Wint.
0
 
LVL 2

Accepted Solution

by:
RichardLinnell earned 2000 total points
ID: 13439163
Is anyone actually going to address the question?

Your Lead developers Static method approach is the same as Microsoft's Sample Data Access Layer (which you'll find on MSDN).

One of the strongest arguments I can think of for not going down the real OO route (instantiated Object method calls) is that you are most likely building these layers to break them out into seperate archtectural and physical layers at some point in the future.  If your DAL was remoted in a fairly standard "single call" way you would not be storing state within the object and hence there is no need for an actual instance of the class to exist at all.  

I suppose as a DAL is pretty much stateless by definition anyway,  there isn't much benefit to building any non-static methods into it at all.  If it is all Static the consuming class saves code :

MyDalClass.ExecuteDataset(...)

vs

MyDalClass DAL = new MyDalClass();
DAL.ExecuteDataset(....);

not much of a saving, but a saving anyway.  Also no memory is used up on the instantiation and lifetime of the object for the static method.

I just ran some static v nonstatic tests and could not see any material performance differences,  also the memory differences were not that great either - but these were very small test classes I was using.  

This is a good design question,  I hope that others out there can add some other viewpoints.
0
 

Expert Comment

by:tqvdang
ID: 13439656
I only use static methods in my Utility Class so that I can access directly without create an instance.
For example:
public class Util
{
   public static byte[] encrypt (string strSource) {}
   public static string decrypt (byte[] bData) {}
   public static void blsadj() {}
   public static int kdasjd() {}
}

If just in case I only need to use encrypt and decryp all I have to do is
bData = Util.encrypt("Hello World!");


0
 
LVL 10

Expert Comment

by:jonvaughan
ID: 13446689
I think the text book answer for this is that Static methods work at a Class level and non-static at an instance/Object level.

For these utility functions where it is the service that is important and the Class doesn't have any data attributes of its own then a Static Method can provide the service without the overhead of having to instantiate the object.
You can see alot of these types of services supplied by Static methods in the Conversion functions.

In terms of performance.
It can also remove the memory overhead of having multiple "Utility Objects" hanging around waiting for some work.
There is an overhead in that the Class does get instantiated ( I belive ) for the duration of the call - but as most of these Classes have little or no data footprint that is not such a big thing.

Cheers
Jon

0
 

Author Comment

by:dei1c3
ID: 13677989
Oh my gosh...I completely forgot about this question.  I posted it one day at work and forgot to check it when I got home later.  Apologies for the late response.

Anyway, I accepted the answer that I think best answered the question I actually asked.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses
Course of the Month13 days, 13 hours left to enroll

801 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