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:25

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-12 02:28

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.

查看更多
登录 后发表回答