When should I write Static Methods?

2019-02-12 02:06发布

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?

标签: c# oop
8条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-12 02:09

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.

查看更多
Evening l夕情丶
3楼-- · 2019-02-12 02:15

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.

查看更多
放荡不羁爱自由
4楼-- · 2019-02-12 02:16

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.

查看更多
劫难
5楼-- · 2019-02-12 02:21

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.

查看更多
beautiful°
6楼-- · 2019-02-12 02:21

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楼-- · 2019-02-12 02:24

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.

查看更多
登录 后发表回答