How to decide between C# static and non-static methods?

前端 未结 11 956
闹比i
闹比i 2020-12-24 03:35

[Edit]

My original-question was \"Why to decide between static and non-static? Both do the same...\"

Unfortunately it was edited to a C#-specific question wh

11条回答
  •  無奈伤痛
    2020-12-24 04:09

    In general, when programming using an OO mindset, you're going to want to avoid using static methods. In OOP, the idea is to represent everything as objects, and to give each object a clear set of abilities that represents its core abstraction. Static methods "break" this abstraction.

    Your example talking about a Document class with a copy method is a prime example. I would argue that the correct OO implementation is the first way. That is, to have copy as an instance method like this:

    document1.copy(toPath)
    

    It makes sense that the ability to copy itself is part of a Documents core abstraction. In this way, the client code sending the copy message only has to specify where to copy to, because it is understood that a Document keeps track of where it is located internally. There is no need for that information to be replicated anywhere else, which is a major problem with the third option you present that looks like this:

    Document.copy(fromPath, toPath)
    

提交回复
热议问题