So far, private fields are introduced as follows:
class MyClass {
#privateField = 123;
}
I’d like to propose a small extension: scoped private fields.
The following style is becoming popular in the JavaScript world. It benefits from scoped privacy:
private #data;
function createStringBuilder() {
return {
#data: '',
};
}
function add(sb, str) {
sb.#data += str;
}
function toString(sb) {
return sb.#data;
}
New in this code:
- The keyword
private
in the first line. - The ability to use private fields in object literals.
As a slight downside, you now always need to use the keyword private
:
class StringBuilder {
private #data = ''; // keyword is required
add(str) {
this.#data += str;
}
toString() {
return this.#data;
}
}
On the upside, this gives you the freedom to widen the scope of privacy:
private #data;
class StringBuilder {
#data = ''; // no keyword!
add(str) {
this.#data += str;
}
}
function toString(stringBuilder) {
return stringBuilder.#data;
}
Alternative syntax has been proposed:
- Keyword
private
not needed for “normal” private fields. - Two keywords if you want to widen the scope of privacy:
private
andouter
.
Example:
private #data;
class StringBuilder {
outer #data = ''; // keyword is now required
add(str) {
this.#data += str;
}
}
function toString(stringBuilder) {
return stringBuilder.#data;
}
FP example:
private #data;
function createStringBuilder() {
return {
outer #data: '', // keyword is now required
};
}
function add(sb, str) {
sb.#data += str;
}
function toString(sb) {
return sb.#data;
}
I disagree with using the
#
symbol. It is counter-intuitive. Static fields and methods are declared usingstatic
keyword. Usingprivate
keyword is more intuitive and fits nicely with existingstatic
keyword. Using private keyword is also easier to remember and to read.It is equally weird that you have to specify that keyword when you access the variable. That also goes against existing conventions.