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

Time:05-10

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?

CodePudding user response:

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.

  • Related