Reputation: 25912
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.
Upvotes: 3
Views: 103
Reputation: 88846
Public for things that are part of the public API.
Protected for non-public functions that you want subclasses to be able to call.
Private if you don't want subclasses mucking around with said method (or to even know of its existence).
In C, C++, and C# don't forgot to mark a method virtual if you want a child class to be able to override it.
Upvotes: 0
Reputation: 1391
I think the helpfulness of the public, protected and private keywords is just to make the code more clear.
So you would use public for the API of a class, private to make it clear how to do NOT extend a class and protected in every other case.
A common pragmatic approach is never use private and to use just public or protected.
Upvotes: 0
Reputation: 24419
With any class/object there are:
1. things it does (behaviours)
2. how it does them (implementation)
The world cares about the behaviour of your object. It shouldn't (often) care about how it achieves this behaviour under the hood. Keep implementation details private, and expose behaviours.
Upvotes: 1
Reputation: 38962
Any kind of operation which does not define behaviour of particular object directly but is useful during implementation of object's behaviour is a candidate for private member function.
Upvotes: 0
Reputation: 4244
Basically:
getState()
would fit here.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.Upvotes: 1
Reputation: 63562
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.
Upvotes: 4