'What is the rationale for using per-method/field access specification?
In C++ the access specifier for a field or method is based on its location under the first previously declared access specification:
public:
int my_public_variable;
private:
void secretPrivateOperations();
int internal_counter;
What is the design rationale behind Java specifying access by prepending the access specifier to each method/field?
public int my_public_variable;
private void secretPrivateOperations();
private int internal_counter;
Solution 1:[1]
To add to awksp answer, let's consider a short example. Quite often, you have public API methods implemented with private methods you don't want to expose. You most often want the code of these methods to be close to each other to make the code easier to read, if you don't, here's what it can look like :
public:
void api1() {
do_some_stuff();
private_method();
some_other_stuff();
}
void api2() {
do_something();
}
int api3() {
int i = a_computation();
return i + A_CONSTANT;
}
private:
void private_method() {
do_clever_stuff();
api1_implementation_details();
}
This is not great to read, private_method is far from the only method which uses it, api1. This public/private division of the code does not make any logical sense. You want your code to be organized by its logic, not by the visibility of the methods.
I very much prefer seeing this :
// I can read the whole logic of this method without any clutter
public void api1() {
do_some_stuff();
private_method();
some_other_stuff();
}
private void private_method() {
do_clever_stuff();
api1_implementation_details();
}
// and so on...
Solution 2:[2]
Compare:
public:
T a();
T b();
...
T z();
versus
public:
T a() {
<lots of code>
}
T b() {
<lots of code>
}
protected:
T c() {
<more code>
}
public:
T d() {
<more code>
}
If you "factor out" the access specifiers like this, things can get pretty nasty pretty quickly. Yes, indentation helps. Yes, you have Ctrl-F. But there still can be a lot of noise to look through (multi-thousand line files, for example), and having to take your mind off of your task just to look for that kind of thing probably wouldn't help productivity.
Java and C++ Java deal with it in different ways. Java keeps access specifiers local, so knowing what method you're working on is enough to determine scope. C++ stuffs declarations together so the access specifier can be "factored out". It may not be as nice when implementing methods, but it's much more concise in header files, and possibly easier to grok too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
