问题
I've read a few threads related to the question by I'm still not sure what's better for the current situation. I have two simple classes:
File:
string name;
long size;
Folder:
string name;
IList<File> files;
IList<Folder> folders;
If I want to implement a method which calculates the contents size of a folder, should I implement it as an instance or as a static member. The implementation needs a Folder object as a sole parameter and it does not change any state of the variable so I'm thinking of making it static but I'm not sure if this is the right step.
回答1:
You can make a comparison with something that describe your problem.
Calculate something when i give you a parameter.
The first thing that comes up in my mind and do a similar thing is Math.Pow which is a static method.
If you want to do Folder.Size(folder);
than you can make it static.
If the method is inside Folder
the problem is different.
Calculate something when i have something
The first thing that i think is Count (although this is a property), this is not static because this calculate something that is unique for every class.
If you want to do Folder.Size
or Folder.Size()
than, non static is your way to go.
Conclusion: Use static when a method don't belong to a class.
回答2:
in this case no, since the size needs a Folder object and you must instantiate one, then add a method like CalculateSize()
or GetSize()
inside the class itself.
回答3:
The most typical, OOP-ish, way to go here is an instance method. You shouldn't pass any parameters in but use this
instead.
Using a static
method within the Folder
class itself would be counter-intuitive and possibly break encapsulation principles. The reason is, your method primarily operates on a specific Folder
instance, and no decoupling of the funcionality away from the Folder
class seems to be necessary in such a trivial case. The only valid case would be to support returning a fallback value, such as 0
, in case a null
reference would be passed in. However, in most cases being tolerant to such inputs causes problems later in the program's control flow.
回答4:
You don't have to go full OOP and just do it with static.
来源:https://stackoverflow.com/questions/29461572/should-i-make-a-method-static