tags:

views:

1786

answers:

7

So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields.

One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:

var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg");

As for static fields, is creating singelton-objects their best use?

+9  A: 

It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.

EDIT: From stevemegson in the comments

A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.

Lou Franco
A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.
stevemegson
+9  A: 

Static methods are usually useful for operations that don't require any data from an instance of the class (from this) and can perform their intended purpose solely using their arguments.
A simple example of this would be a method Point::distance(Point a, Point b); that calculates the distance between two points and don't require an instance.

Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.

shoosh
+3  A: 

I would say use static methods whenever you have functions which are independent of the state of the instance, ie. doesn't depend on any instance fields.

The less non-local state that a method depends on, the easier it is to understand, so static is a helpful signal to the reader of the code.

JacquesB
If I understand this correctly, you are saying _alawys_ use static methods when you can. But that doesn't feel right. There are plenty of cases in the .NET Base Class Libraries where methods could be static but aren't.
Chris Smith
@Chris, that doesn't mean they did it right.
Wedge
@wedge - agreed, I was debugging through some of the .NET source today and it made me shiver in places, also made feel better about some of the dodgy code I've written too :)
Kev
+4  A: 

I keep it clear by remembering that instance methods work on/inside individual objects while static methods do something for the Class.

In the case of LoadFromFile(), you want a static method because you want a null reference if the load fails - the instance doesn't exist yet. If you implemented it as a constructor, you'd have to throw an Exception on failure.

Other good uses for statics: Compare(obj a, obj b), Delete(obj a) for data objects (an object can't delete itself since its reference is still around), or static Classes for procedural code that honestly can't be modeled in an object.

Corbin March
A: 

You may use static methods when the client of the class do not have an instance of the class to work with. For instance the Singleton design pattern is used to ensure that only one instance of a class exist in the system. It requires that the constructors of the Singleton be private so that no instances can be created by the client.

So if you cannot create an instance how do you access the instance methods of the class? By calling a static method that returns the Singleton instance of the class.

This is of course just one scenario but there are many others.

Vincent Ramdhanie
A: 

Here are some examples of when you might want to use static methods:

1) When the function doesn't make use of any member variables. You don't have to use a static method here, but it usually helps if you do.

2) When using factory methods to create objects. They are particularly necessary if you don't know the type to be created in advance: e.g.

class AbstractClass {
    static createObject(int i) {
        if (i==1) {
           return new ConcreteClass1();
        } else if (i==2) {
           return new ConcreteClass2();
        }
     }
}

3) When you are controlling, or otherwise keeping track of, the number of instantiations of the class. The Singleton is the most used example of this.

4) When declaring constants.

5) Operations such as sorts or comparisons that operate on multiple objects of a class and are not tied to any particular instance.

6) When special handling has to be done before the first instantiation of an object.

DJClayworth
A: 

You should use static methods whenever you have a function that does not depend on a particular object of that class.

There is no harm in adding the static keyword: it will not break any of the code that referred to it. So for example, the following code is valid whether or not you have the 'static' keyword:

class Foo
{
    public Foo(){}
    public static void bar(){}  // valid with or without 'static'
    public void nonStatic(){ bar(); }
}

...
Foo a = new Foo();
a.bar();

So you should add 'static' to whatever methods you can.

David Grayson