Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to declare methods as private

I am looking for specific and exact rules to determine how a method's visibility can be declared. This is not language agnostic, it applies to the standard OOP languages.

like image 967
Zombies Avatar asked Apr 15 '26 13:04

Zombies


2 Answers

A good rule to follow would be:

Members should not have more accessibility than they need.

Start with private and make them more accessible as the need arises.

like image 72
hunter Avatar answered Apr 18 '26 07:04

hunter


Basically:

  • Public is for when the method must be accessible by an outside class. Something like getState() would fit here.
  • Private is for when the method should not be accessible by any other class, something like changeState(...). Generally this relates to the actual alteration of an object's contents - maybe you'll have a public setX(int x) that just calls the private setXInternal(int x), that way you can have extra type-checking/safety/etc. To be safe you might as well make everything private until it has to be otherwise.
  • Protected is basically "public to child classes, private otherwise". Could go either way.
like image 43
Toomai Avatar answered Apr 18 '26 07:04

Toomai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!