Is it fair to say that it is good practice to default everything to private up when defining a class?
For example, for my public interface I would set my class something like this:
class foo {
private var x
private var y
//even get and set are private,
//public only if necessary
private get/set method for variables
//main function
private coreFunc () {...}
//helper function
public callCoreFunc() {
coreFunc()
}
}
I'm used (and got used from my algorithm teacher) that everything in a class should be private, except for the methods that the user need to call (with wrapped helper function.)
Is this a good way to see "public interface" or is this too strict?
1 Answer 1
It's certainly true that it's best to make everything private unless it needs to be public is a good starting point.
But making important member functions private, and then writing public wrapper functions so that they may be called, doesn't really achieve anything.
From a code efficiency perspective, you've added an extra function call each time the member function is called, and you've bloated your code base with extra functions.
From a code hiding point of view, you haven't actually hidden anything. In languages (such as Java) which don't have separate "headers" and "bodies" it makes no difference - if the user can see the wrapper then they can see the code. In languages that do have separate headers, such as C++, then the wrapper will be in the same body as the function it wraps. So the user will see both if they have access to the body, or neither if they don't.
Unless you're selling proprietary software, private in OO isn't really about hiding code from people. It's about clearly separating the bits that are the public API of a function from the implememtation details, and making sure the caller can only access the bits they are intended to.
Explore related questions
See similar questions with these tags.
coreFunc
topublic
and let the compiler (by throwing an error for attempts to access a private member) and documentation (by not mentioning the private members as part of the API) do the rest.