When is it appropriate to use static methods?

  • Thread starter Thread starter Tom
  • Start date Start date
Tom,

Static methods are methods that do not share any variables. the are the
same as VB6 sub routines that our outside of a class.

Example:
class Foo
{
private string thisTest = "test";
public string MyString()
{
return thisTest;
}

public static MyStaticString()
{
return "test";
}
}

usage:

when using a static method you can just call
string test = Foo.MyStaticString();

if it is not static you have to create and instance of the class

Foo myFoo = new Foo();
string test = myFoo.MyString();

Basically is all boils down to memory usage. a static method is shared,
where as a non-static method gets created for every instance of the class.
Hope this makes sense?
 
Use a static method when the method does not belong to a specific object.

For example, if you look at the Math class in .NET framework, you will see
that all methods are static. Why? Because there is no reason to must create
an object to use the methods. Why would you want to create an object of the
Math class, when all you want is the absolute value of something? No, there
is no reason to do this, and therefore, the method is static.

So when you design a class, ask yourself:

Does this method belong to an object, or the class itself?

A method belongs to an object, if it modifies the state of the object. If
the method does not modify a specific object, it can most likely be static.

Another example, suppose that you want to know how many objects of a class
that is created (don't ask me why...). For this task, you could create a
static method GetNumberOfObjects() (and you obviously need a static field,
and some code in the constructor too). Why would i have it static, you might
ask. Well, answer the above question, and you will see. The method does not
belong to any specific object. Additionally, it does not modify any object.

I hope this makes sense.
 
Kristofer Gafvert said:
Use a static method when the method does not belong to a specific object.

What if the class is a singleton?

For instance, I have a WinForm application that does not allow multiple
instances of the application to run on the same workstation. This
application uses a Business Object singleton that caches global variables,
such as a reference to a DataSet that can be used by multiple MDI child
forms.

It doesn't seem particularly useful or efficient to create a new instance
every time I want to use one of the methods in this singleton.
 
I would say that the same "rules" apply, no matter if it is a singleton or
not.

But, remember that a static method is not a substitute for not having a
proper class design. Is the method(s) we are talking about really relevant
for the class? Does they belong to the class, or to another (not yet
created?) class?
 
[snip]
Basically is all boils down to memory usage. a static method is shared,
where as a non-static method gets created for every instance of the class.
Hope this makes sense?

This is not correct. The code is always shared whether it's static or not.
You're thinking of data, there's only one instance of static data,
non-static data is created for every instance.

John Vottero
 
My fault, that is what I was trying to get at.

Thanks for clearing that up.

John Vottero said:
[snip]
Basically is all boils down to memory usage. a static method is shared,
where as a non-static method gets created for every instance of the class.
Hope this makes sense?

This is not correct. The code is always shared whether it's static or not.
You're thinking of data, there's only one instance of static data,
non-static data is created for every instance.

John Vottero
 
IMO, statics are simplified equivalents of singletons. They grow from
globals - functions or variables. There is not much more.
I would suggest statics
- when you need global method, property or function
- when you need global variable
- when you need singleton, which exists during whole application lifetime

I found it easier to code singletons using statics. Excellent examples -
such classes like SystemInformation or Environment.

HTH
Alex
 
If you want to be able to cast the singleton object to an Interface or base
class, then you shouldn't create every member as static.
 
Singleton idea was to create a pattern, which allows you to have only one
instance of specific object during application lifetime. Static is object
(function) independent of any objects which might exist or not during
application lifetime. Statics exist and function always. So, there is some
difference - however, not very important for me. People fought with issues
with globals and invented singletons.

As about your question - general answer for general question - it depends.
If your singleton is providing global functionality - why not? If you want
some methods to be unavailable when singleton doesn't exist - might happen -
then no.

HTH
Alex
 
Good point,

as of today it is not possible to declare static method as virtual or
override. I am not very deep in OO internals, but I wonder why it is so.
Why static method can't be virtual or overriden in derived class? Maybe it
has not much sense, however doesn't seem also too much against OO
principles. It could be fun to be able to override static methods in system
classes - seems like ideal system hook functionality.

Another point is impossibility to declare static interface method. I seem
not to grasp yet if and when it could be useful. Anybody can throw in some
ideas?

Alex
 
Tom said:
What if the class is a singleton?

For instance, I have a WinForm application that does not allow multiple
instances of the application to run on the same workstation. This
application uses a Business Object singleton that caches global variables,
such as a reference to a DataSet that can be used by multiple MDI child
forms.

It doesn't seem particularly useful or efficient to create a new instance
every time I want to use one of the methods in this singleton.

If your code even *allows* you to create a new instance each time, it's
no longer a singleton, by definition.
 
AlexS said:
Good point,

as of today it is not possible to declare static method as virtual or
override. I am not very deep in OO internals, but I wonder why it is so.
Why static method can't be virtual or overriden in derived class? Maybe it
has not much sense, however doesn't seem also too much against OO
principles. It could be fun to be able to override static methods in system
classes - seems like ideal system hook functionality.

Another point is impossibility to declare static interface method. I seem
not to grasp yet if and when it could be useful. Anybody can throw in some
ideas?

The addresses of static methods are compiled directly into your code
when they are called. Virtual and override methods (as well as
interfaces) use indirect v-tables to lookup method addresses for each
object type.
One could argue that the compiler or JIT could still resolve the
overridden method's address (Base.StaticMtd differently from
SubClass.StaticMtd), but they probably kept this restriction for
simplicity.
 
Jon Skeet said:
If your code even *allows* you to create a new instance each time, it's
no longer a singleton, by definition.

No. I am using the following format to create my singleton:

namespace Company.TWS.BusinessObject
{
public class SummaryBO
{
private static TwsDS _twsDS;
private static string xmlLocation = @"c:\data\tws\tws.xml";
private SummaryBO() {}
public static readonly SummaryBO Instance = new SummaryBO();
public static TwsDS twsDS { get { return _twsDS; } }

[...]
}
}
 
Tom said:
Jon Skeet said:
If your code even *allows* you to create a new instance each time, it's
no longer a singleton, by definition.

No. I am using the following format to create my singleton:

namespace Company.TWS.BusinessObject
{
public class SummaryBO
{
private static TwsDS _twsDS;
private static string xmlLocation = @"c:\data\tws\tws.xml";
private SummaryBO() {}
public static readonly SummaryBO Instance = new SummaryBO();
public static TwsDS twsDS { get { return _twsDS; } }

[...]
}
}

I'm not sure why you've got an instance at all, if everything's static.
The normal singleton pattern would have the _twsDS and twsDS
field/property as an instance, and you'd refer to it using

SummaryBO.Instance.TwsDS

That *doesn't* create an instance each time.
 
Jon Skeet said:
I'm not sure why you've got an instance at all, if everything's static.
The normal singleton pattern would have the _twsDS and twsDS
field/property as an instance, and you'd refer to it using

SummaryBO.Instance.TwsDS

That *doesn't* create an instance each time.

OK. I think I understand.

It sounds like what you are saying is create all methods and fields as
normal instance fields within the singlton rather than static (as I was
doing), and the mere fact that it is a singleton will give the smae effect
as acheived by creating all static.

Is that correct? (If so, it does seem much cleaner)
 
Tom said:
OK. I think I understand.

It sounds like what you are saying is create all methods and fields as
normal instance fields within the singlton rather than static (as I was
doing), and the mere fact that it is a singleton will give the smae effect
as acheived by creating all static.

Is that correct? (If so, it does seem much cleaner)

Yup, that's right.
 
Back
Top