1

When should I mark the static method of a specific class as private other than public?

What aspects should I consider when making such considerations.

What are the advantages for mark the static method as private?

Any simple example would be appreciated, which could help me fully understand this matter.

UPDATE:

As per this answer, which says that[emphasise mine]:

This function could easily have been made freestanding, since it doesn't require an object of the class to operate within. Making a function a static member of a class rather than a free function gives two advantages:

It gives the function access to private and protected members of any object of the class, if the object is static or is passed to the function;

It associates the function with the class in a similar way to a namespace.

How to fully understand the statements above?

John
  • 2,963
  • 11
  • 33
  • 2
    ***When should I mark the static method as private other than public?*** When you want only your class to access the static – drescherjm May 10 '22 at 02:32

1 Answers1

2

The general rule for methods (static or otherwise) is to make them private if possible — i.e. unless you absolutely need them to be callable from other classes (which is to say, you need them to be part of your class’s public API)

The reason for making as much as possible private is simple: in the future, you’ll be able to change anything that is private, without breaking a bunch of other classes that were written to call the old version of the method. Changing a public method is more problematic, because other classes might be depending on it.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • I carefully read some similar posts and more questions raise. Could you please give me some help about the updated question? – John May 10 '22 at 03:23
  • I don't think I can give a useful answer to "how to fully understand the statements" -- keep reading them and thinking about what they say, I guess? If you have a more specific question, I could try to answer that. – Jeremy Friesner May 10 '22 at 04:11
  • 2 more reasons: 1) if a function is (acidentally) public then eventually some code will call it that shouldn't. 2) If nothing outside the class calls a public method you get no warning or error that the method could be private. If something outside the class calls a private method you get a compile error and then can decide if the call is wrong or the method should be protected or public. – Goswin von Brederlow May 10 '22 at 17:20