#Google Analytic Tracker

Pages

Apr 9, 2007

Why use Private Static Method

When I was refactoring old company project code (prior of using Resharper), Resharper always give me this warning, suggesting me convert private method into a private static method.

For me, I understand the advantage of using a public static method. A public static method allow user to execute the method without object instantiation. What about a private static method, what is its advantage of using it? I naively ask the following questions:

1. Is the performance better when using a private static method instead of private method?

2. Does it use less memory space than a non static function?

If we talks about static classes, static variables or public static methods, I definitively understand why we have to use them in certain situation. Let me provide my own explanations for these items in the following order:

Static Variable

- a variable that declares as static will retain its value though out the application runtime. Since it is a static, the information of this variable is stored on the stack (memory), and not on a heap (memory). Static Variable only initialize once, and all object of its class can share this static variable.

Static Method

- a method that only access static variable. Hence, static method can not access to non-static variable inside your class. You will get a compiling error if you do the following:

BAD CODING EXAMPLE:

   1: public class MyNonStaticClass
   2: {
   3:     private int myNonStaticVar;
   4:     private static int myStaticVar;
   5:     
   6:     public static void MyStaticMethod()
   7:     {
   8:         myStaticVar = 15; // Static method can access myStaticVar
   9:         myNonStaticVar = 10; // Compiling ERROR!!! Static method cannot access non-static variable
  10:     }        
  11: }

Static Class

a class only contains static variable and static methods. No doubt,its because it is declared as a static class. You can not instaniate a static class to any new object. The memory of this class is allocated on the stack (unlike an object which is created on the heap). Static class is a sealed class (at least that's what I know about C#), which means it can't be derived into new classes.

STATIC CLASS EXAMPLE:

   1: public static class MyStaticClass
   2: {
   3:     private static int myStaticVar = 10;
   4:     
   5:     public static int DoSomething()
   6:     {
   7:         return myStaticVar++;
   8:     }
   9: }

So let get into a bit more examples

Static Variable in a Non-Static Class

So, what happen when you declare a static variable in a non-static class? First, since it is a non-static class, you can instaniate new objects as usual and yet, all these object SHARES the same static variable.  In addition, static variable is only initialized ONCE, and it has to be initialize before any object is instantiated. So pay attention on how your static variable initialized. To initialize a static variable, you can do it inline or do it in a STATIC Constructor.

STATIC VARIABLE INITIALIZATION EXAMPLE:

   1: public static class MyStaticClass
   2: {
   3:     private static int myStaticVar = 10; // inline initialization
   4:     private static int mySecStaticVar;
   5:     
   6:     //static contructor
   7:     static MyStaticClass()
   8:     {
   9:         mySecStaticVar = 20;
  10:     }
  11: }

We don't know when exactly static variable is initialized, but it has to be initialize before any instance is created, and after the assembly is loaded. Note that STATIC CONSTRUCTOR doesn't take any parameter nor it has privilege access modifier (public, private, internal). This is because it is a class initialization, not a object initialization. Moreover, Static Constructor can also be added in a non-static class:

A SIMPLE STATIC CONTRUCTOR IN A NON-STATIC CLASS:

   1: public class MyNonStaticClass
   2: {
   3:     private int myNonStaticVar;
   4:     private static int myStaticVar;
   5:     
   6:     static MyNonStaticClass()
   7:     {
   8:         myStaticVar = 10;
   9:     }
  10:  
  11:     public MyNonStaticClass()
  12:     {
  13:         myNonStaticVar = 30;
  14:     }
  15: }

STATIC VARIABLE BEING SHARED EXAMPLE:

   1: public class MyNonStaticClass
   2: {
   3:     private static int mySharedVariable;
   4:  
   5:     public int MySharedVariable
   6:     {
   7:         get { return mySharedVariable; }
   8:         set { mySharedVariable = value; }
   9:     }
  10:  
  11:     static MyNonStaticClass()
  12:     {
  13:         mySharedVariable = 10;
  14:         Console.WriteLine("MyNonStaticClass: running static constructor");
  15:     }
  16:  
  17:     public MyNonStaticClass()
  18:     {
  19:         Console.WriteLine("MyNonStaticClass: running normal constructor");
  20:     }
  21: }
  22:  
  23: class Program
  24: {
  25:     static void Main(string[] args)
  26:     {
  27:         MyNonStaticClass myNonStaticClass1 = new MyNonStaticClass();
  28:         MyNonStaticClass myNonStaticClass2 = new MyNonStaticClass();
  29:  
  30:         // Print out myNonStaticClass2.MySharedVariable:
  31:         Console.WriteLine("\nInitially, myNonStaticClass1.MySharedVariable = {0}\n", myNonStaticClass1.MySharedVariable);
  32:         
  33:         // Change myNonStaticClass1.MySharedVariable, which would ultimately chang
  34:         myNonStaticClass2.MySharedVariable = 999;
  35:         Console.WriteLine("Now set myNonStaticClass2.MySharedVariable to 999\n");
  36:  
  37:         // Print out myNonStaticClass2.MySharedVariable:
  38:         Console.WriteLine("result: myNonStaticClass1.MySharedVariable = {0}\n", myNonStaticClass1.MySharedVariable);
  39:         
  40:     }
  41: }
  42:  

If you run the example above, you would see the following output:

MyNonStaticClass: running static constructor

MyNonStaticClass: running normal constructor

MyNonStaticClass: running normal constructor

Initially, myNonStaticClass1.MySharedVariable = 10

Now set myNonStaticClass2.MySharedVariable to 999

result: myNonStaticClass1.MySharedVariable = 999

Press any key to continue . . .

Static Variable in a Static Class

If you have a static class, you have to use static variable only.  So, when to use a static class? You can use it as a utility class which provide basic inputs and output function that doesn't require object creation.  Another situation that I can think of is to use a static class provide a configuration and setting though out the entire application. That way, any other classes or object can access this static class and for sure they will get the same settings from the class. Third one is to set up a singleton design pattern such that all functionality and state of this class is shared in your application.

Situation of creating a Static Variable in a non-static class

If you want to share variables across all instainated object, then create a static variable in a non-static class. This way, all objects will able to share the static variable. However, beware of running into variable synchronization issue with multithreaded programming. Although I am not an expert in this field yet, but this is my word of caution. When multiple threads accessing the same variable, they don't always get the same value in time, because each thread actually has its own variable cache. Each time a thread modify a variable, this value need some time before it is synchronized with other thread's memory cache. (Correct me if I am wrong)

Also, if you want to keep track how many instance of the object is created, you can increment a static variable inside a class contructor.

So, why we have a Private Static Method?

This question has bugged me for a while, because I  don't see the any advantage of using static private method compare with a non-static private method. Unlike a public static method, which can be called without object instances. To access a public static method, you can just access it thought its class name:

EXAMPLE OF ACCESSING A PUBLIC STATIC METHOD

   1: public static class MyStaticClass
   2: {    
   3:     public static int DoStaticMethod()
   4:     {
   5:         return System.Writeline("Executing a static method");
   6:     }
   7: }
   8:  
   9: public class SomeOtherClass
  10: {
  11:     void RunStaticMethod()
  12:     {
  13:         //Accessing a static method though class name
  14:         MyStaticClass.DoStaticMethod();
  15:     }
  16: }

I mean, since static private and non-static private doesn't get exposed to other class, why would I want to make a non-static private method into a static private method if possible?

I encountered this thought because ReSharper gives me warning, or more a suggestion when it detects a method can be made as static private method. Resharper able to determine this by analyzing the variable declaration that I used inside the method scope. If the method doesn't access any global variable, or it only access local or static global variable, then Resharper would suggest you to make this private method into a static private method.

I began to think if it make any different a method is make to static.  Initially, it wasn't convincing since I don't see making the method static makes the program run faster, or save memory.

However, after thinking more about it, marking a function as static actually helps me analysis the code. When I see a method is static, I know that the state of the function only access static and local variable. In addition, if you want to call a method in a static contructor, the method has to be a static (private or public). Further more, I read an article that most of the compiler run more efficient when compiling a static method. I guess it is probably because static method doesn't access reference variable on the heap, instead, it only need to access memory on a stack. If I remember it correctly, it takes more instruction (machine) code to resolve the relative address of a reference variable than a static variable. 

One last word

Be conscience when using static member. Since static member is accessed by all object instances and thread, it should be protected by using locks or some kind of synchronized methods to prevent deadlocks in your application.

Reference

C# Threading Best Practices

Java Note on Static Method

2 comments:

warren said...

I have come across an instance where it might be used - perhaps i am wrong.

Here is my scenario:
I am calling a public static method which in then needs to call another method.

My secondary method is going to be private as it is only needed within my class of my (first) public static method.

Since the (first) public static is not instantiating any class, my (second) private method needs to be called statically and can stay private

^_^ Warren

Dicky said...

This article was written 4+ years ago, so the question of using private static method may not longer be relevant with new experience.

Warren, there isn't anything wrong on how you use it in your scenario. Over the last 4 years, I do find advantage of using private static methods. Not because it has any performance or memory usage advantage, but rather it makes the class more readable, and more maintainable. It also give you more flexibility on how you want your class to look like.

One scenario is you can reduce a complicated static public method by breaking it into multiple private static method. Since the method is marked a static, you can immediately tell this method can only access static variables within the class without worrying about non-static variables.