473,382 Members | 1,165 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

When is it appropriate to use static methods?

Tom
This is not intuitivelly clear.
Nov 16 '05 #1
17 51373
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?
"Tom" <nf*@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
This is not intuitivelly clear.

Nov 16 '05 #2
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.

--
Regards,
Kristofer Gafvert - IIS MVP
http://www.ilopia.com - When you need help!
"Tom" <nf*@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
This is not intuitivelly clear.

Nov 16 '05 #3
Tom

"Kristofer Gafvert" <kg******@NEWSilopia.com> wrote in message
news:u%****************@TK2MSFTNGP09.phx.gbl...
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.
Nov 16 '05 #4
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?

--
Regards,
Kristofer Gafvert - IIS MVP
http://www.ilopia.com - When you need help!
"Tom" <nf*@nospam.com> wrote in message
news:eg*************@TK2MSFTNGP11.phx.gbl...

"Kristofer Gafvert" <kg******@NEWSilopia.com> wrote in message
news:u%****************@TK2MSFTNGP09.phx.gbl...
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.

Nov 16 '05 #5
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

"Tom" <nf*@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
This is not intuitivelly clear.

Nov 16 '05 #6

"Ben Dewey" <be*******@scientiae.com> wrote in message
news:eW**************@tk2msftngp13.phx.gbl...

[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
Nov 16 '05 #7
My fault, that is what I was trying to get at.

Thanks for clearing that up.

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:Os**************@TK2MSFTNGP10.phx.gbl...

"Ben Dewey" <be*******@scientiae.com> wrote in message
news:eW**************@tk2msftngp13.phx.gbl...

[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

Nov 16 '05 #8
Tom
Should I make all the methods in a singleton static?

"AlexS" <sa***********@SPAMsympaticoPLEASE.ca> wrote in message
news:es**************@TK2MSFTNGP11.phx.gbl...
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

"Tom" <nf*@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
This is not intuitivelly clear.


Nov 16 '05 #9
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

"Tom" <nf*@nospam.com> wrote in message
news:eE**************@tk2msftngp13.phx.gbl...
Should I make all the methods in a singleton static?

"AlexS" <sa***********@SPAMsympaticoPLEASE.ca> wrote in message
news:es**************@TK2MSFTNGP11.phx.gbl...
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

"Tom" <nf*@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
This is not intuitivelly clear.



Nov 16 '05 #10
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.

"Tom" <nf*@nospam.com> wrote in message
news:eE**************@tk2msftngp13.phx.gbl...
Should I make all the methods in a singleton static?

"AlexS" <sa***********@SPAMsympaticoPLEASE.ca> wrote in message
news:es**************@TK2MSFTNGP11.phx.gbl...
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

"Tom" <nf*@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
This is not intuitivelly clear.



Nov 16 '05 #11
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

"Andy Gaskell" <pubb AT hotmail DOT com> wrote in message
news:eM*************@tk2msftngp13.phx.gbl...
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.

"Tom" <nf*@nospam.com> wrote in message
news:eE**************@tk2msftngp13.phx.gbl...
Should I make all the methods in a singleton static?

"AlexS" <sa***********@SPAMsympaticoPLEASE.ca> wrote in message
news:es**************@TK2MSFTNGP11.phx.gbl...
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

"Tom" <nf*@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
> This is not intuitivelly clear.
>
>



Nov 16 '05 #12
Tom <nf*@nospam.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #13
"AlexS" <sa***********@SPAMsympaticoPLEASE.ca> wrote in message news:<eS**************@TK2MSFTNGP09.phx.gbl>...
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.
Nov 16 '05 #14
Tom
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Tom <nf*@nospam.com> wrote:

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; } }

[...]
}
}
Nov 16 '05 #15
Tom <nf*@nospam.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Tom <nf*@nospam.com> wrote:

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 - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #16
Tom

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
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)
Nov 16 '05 #17
Tom <nf*@nospam.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: Axehelm | last post by:
Okay, I'm in a debate over whether or not static methods are a good idea in a general domain class. I'm personally not a fan of static methods but we seem to be using them to load an object. ...
3
by: Steven D'Aprano | last post by:
I've been doing a lot of reading about static methods in Python, and I'm not exactly sure what they are useful for or why they were introduced. Here is a typical description of them, this one...
8
by: Steven Livingstone | last post by:
Anyone able to explain to me why you cannot define an interface that can then be implemented using static methods? I understand the C# CLS states this, but just interested in the reasons behind...
3
by: Jay | last post by:
Why are there static methods in C#. In C++ static was applied to data only (I believe) and it meant that the static piece of data was not a part of the object but only a part of the class (one...
9
by: Clint | last post by:
Hey all - Excuse the cross-post ... I'm not sure what the appropriate newsgroup would be for this question. I have a question that I'm not quite sure how to ask. For all I know, I have the...
4
by: Joe Fallon | last post by:
In another post Kevin Spencer stated: "one should be careful of using static fields, properties, and methods, by understanding what the implications of such are (e.g. locking static variables when...
15
by: dn | last post by:
I'm starting an n-tier application with an ASP.NET 2.0 presentation layer, a business layer, a data access layer, and a SQL Server 2005 database, and I have a question. In the business and data...
12
by: chandu | last post by:
hello, i want to know usage of static methods in a class. is it advantageous or disadvantage to use more static methods in a class. thank u
7
by: intrader | last post by:
I have the following small classes: //----------------code--------------- using System; using System.Collections.Generic; using System.Text; namespace ValidatorsLibrary { public class...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.