1

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.

zhulien
  • 507
  • 2
  • 8
  • 17

4 Answers4

1

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.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
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.

adricadar
  • 9,971
  • 5
  • 33
  • 46
1

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.

YazX
  • 444
  • 4
  • 12
0

You don't have to go full OOP and just do it with static.