When should I write Static Methods?

2019-02-12 02:26发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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.



回答5:

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.



回答6:

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.



回答7:

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.



回答8:

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.



标签: c# oop