Conceptcore
Encapsulation
Also called encapsulation, access control, access modifiers, visibility, private members, data hiding, opaque types.
Encapsulation keeps the data of an object behind the operations that may change it, so the object can keep its invariants and change its implementation without breaking callers.
- Applies to
- core-languages
Idea
Encapsulation keeps the data of an object together with the code that may change it, and stops other code from changing the data directly. Outside code works through a small set of operations, the interface, and the object keeps its fields and helpers to itself. Two benefits follow. The object can guarantee rules about its own state, its invariants, because every change goes through code that checks them. And the implementation can change without breaking callers, because no caller depends on it. Languages enforce encapsulation with access modifiers, module boundaries or closures, or leave it to convention.
class Account:
"""Invariant: balance == sum(history) and balance >= 0."""
def __init__(self):
self._balance = 0 # the underscore says: not part of the interface
self._history = []
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._history.append(amount)
self._balance += amount
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("insufficient funds")
self._history.append(-amount)
self._balance -= amount
@property
def balance(self): # read access without write access
return self._balance
def consistent(self):
return self._balance == sum(self._history) and self._balance >= 0
a = Account()
a.deposit(100)
a.withdraw(30)
print(a.balance, a.consistent())
try:
a.withdraw(500) # the method guards the invariant
except ValueError as e:
print("refused:", e)
try:
a.balance = 10**6 # the property has no setter
except AttributeError as e:
print("refused:", e)
a._balance = 10**6 # Python does not stop code that ignores the convention
print(a.balance, a.consistent())
def make_counter(): # a closure gives state that no outside code can reach
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
tick = make_counter()
tick()
print(tick(), hasattr(tick, "count"))
70 True
refused: insufficient funds
refused: property 'balance' of 'Account' object has no setter
1000000 False
2 False
Account keeps two fields that must agree: the balance and the list of changes. The methods deposit and withdraw change both together and refuse a change that would make the balance negative, and the property balance gives read access only. While all code goes through these operations, consistent() stays true. The line that writes _balance directly breaks the invariant, and Python allows it, because its privacy is a convention. The counter at the end hides its state in a closure, where no outside code can name it.
How it works
Interface and implementation. An encapsulated type has two parts. The interface is the set of operations that other code may use, with their meaning. The implementation is the fields, the helper functions and the algorithms behind them. Callers depend only on the interface, so the implementation can change, for example from a list to a tree or from a stored value to a computed one, without a change to any caller. This is the idea of information hiding applied to a single type.
Invariants. An invariant is a rule about the state of an object that holds whenever no operation is running: a balance is not negative, a sorted list is sorted, a count matches the number of items. If only the object's own methods can change its fields, then to prove that the invariant always holds, a programmer must check only those methods: each constructor must establish it, and each method must keep it. Without encapsulation, any line of the program might break it.
Access control. Most languages with classes mark each member with an access level. Java's tutorial states the purpose: "Access level modifiers determine whether other classes can use a particular field or invoke a particular method."1 The common levels are private to the class, visible to subclasses, visible to the package or module, and public. Rust makes privacy the default: "By default, everything is private", and "If an item is private, it may be accessed by the current module and its descendants."2 Go uses the case of the first letter: "An identifier may be exported to permit access to it from another package", and a name is exported when it starts with an upper case letter.3 In C++, Java, C# and Rust the check happens at compile time, and in JavaScript, whose # fields are "enforced by JavaScript itself", it happens when the engine parses the code.4
Convention instead of enforcement. Python has no access modifiers. Its tutorial says: "“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python." Instead, "a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API".5 Linters, editors and readers follow the convention. Smalltalk takes the opposite position for fields: instance variables are visible only to the object's own methods, and all methods are public.
Encapsulation leaks through references. A private field that holds a reference to a mutable object protects only the reference. If a constructor stores a list that the caller still holds, or a getter returns the internal list, outside code can change the object's state without calling any method. Defensive copies, read-only views and immutable types close these leaks. The wrong blocks in the Python, Java and Go files show them.
Properties and accessors. A getter and setter pair lets a class check every write and compute values on read. Properties in Python, C# and Kotlin, and get and set in JavaScript classes, make these methods look like fields, so a class can start with a plain field and add checks later without a change to callers. A getter for every field, with a setter that checks nothing, hides the name of the field but not the design, and gives little of the benefit.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | Private, protected and public are checked by the compiler only and vanish from the output, while the. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Private, protected, internal and public, with public as the default and internal for one module; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Native | GRANT and REVOKE control which roles may read or change a table, and views and stored procedures can expose a part of the data. |
| Bash | Idiom | Local makes a variable visible only in a function and the functions it calls, and readonly stops later assignment, but there are no objects. |
| PowerShell | Idiom | Class members can be hidden, which removes them from default output and completion but not from access; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Idiom | A closed shadow root hides the inner elements of a custom element from the scripts of the page. |
| CSS | Idiom | Styles inside a shadow root do not apply outside it, and the styles of the page do not reach into it. |
| Regular expressions | Does not apply | A pattern has no state to hide. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | _name by convention; properties; name mangling for __name |
| JavaScript | native | #private fields and methods; closures |
| TypeScript | native | private and protected checked at compile time; #private |
| Java | native | private, package, protected, public; module exports |
| Kotlin | native | private, protected, internal, public |
| C# | native | six access levels; accessors with their own level |
| Go | native | unexported lower case names, per package |
| Rust | native | private by default per module; pub, pub(crate) |
| C | idiom | opaque pointers; static functions |
| C++ | native | public, protected, private; friend |
| Bash | idiom | local and readonly variables |
| PowerShell | idiom | hidden class members |
| SQL | native | GRANT and REVOKE; views and procedures |
| Regex | n/a | no state |
| HTML | idiom | closed shadow roots |
| CSS | idiom | styles scoped to a shadow root |
Every example file builds the same bank account, with a balance that must not go negative and a history that must agree with it, and then shows what the language does when outside code tries to change the balance directly. Java, C#, C++, Rust and JavaScript reject the access. Go rejects it only from another package, and C rejects it only because the caller does not know the layout of the struct. Python lets it happen.
The unit of privacy differs. In Java, C# and C++ it is the class: a method can read the private fields of any object of its class, not only its own. In Go and Rust it is the package or module, so all code in the module can use the fields of every type defined there. In JavaScript it is the class body. Ruby and Smalltalk restrict access per object, so a method can read the fields of its own receiver only.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius # goes through the setter, so the check runs here too
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError(f"{value} is below absolute zero")
self._celsius = value
t = Temperature(20)
t.celsius = 25 # looks like a field, runs a method
print(t.celsius)
try:
t.celsius = -300
except ValueError as e:
print(e)
class Base:
def __init__(self):
self.__id = "base" # name mangling: stored as _Base__id
def base_id(self):
return self.__id
class Child(Base):
def __init__(self):
super().__init__()
self.__id = "child" # stored as _Child__id: no clash with Base
c = Child()
print(c.base_id(), sorted(vars(c)))
print(c._Base__id) # mangling avoids clashes; it does not enforce privacy
25
-300 is below absolute zero
base ['_Base__id', '_Child__id']
base
This code runs but gives a wrong answer on purpose.
class Team:
def __init__(self, members):
self._members = list(members) # a private copy of the input
def members(self):
return self._members # returns the internal list itself
def size(self):
return len(self._members)
team = Team(["ana", "bo"])
names = team.members()
names.append("mallory") # the caller changes the team's state
print(team.size(), team.members())
3 ['ana', 'bo', 'mallory']
- Verdict: idiom. Python has no access modifiers. A leading underscore marks a name as internal by convention, and tools and readers respect it, but the language does not. A property turns an attribute into a pair of methods, so a class can check every write, as
Temperaturedoes, without changing the code of its callers. Two leading underscores trigger name mangling:self.__idinBaseis stored as_Base__id, so a subclass that uses the same name does not overwrite it. The name stays reachable from outside under its mangled form. - The wrong block returns the internal list from a method. The caller gets the list itself, not a copy, and appending to it changes the state of the team without going through any method. Return a copy, a tuple, or an iterator instead.
#include <iostream>
#include <stdexcept>
#include <vector>
class Account {
public:
void deposit(long amount)
{
if (amount <= 0) throw std::invalid_argument("deposit must be positive");
history_.push_back(amount);
balance_ += amount;
}
void withdraw(long amount)
{
if (amount > balance_) throw std::runtime_error("insufficient funds");
history_.push_back(-amount);
balance_ -= amount;
}
long balance() const { return balance_; }
const std::vector<long>& history() const { return history_; } // read-only view
bool same_balance(const Account& other) const
{
return balance_ == other.balance_; // private is per class, not per object
}
private:
long balance_ = 0;
std::vector<long> history_;
friend void audit(const Account&); // a friend may read the private members
};
void audit(const Account& a) { std::cout << "audit " << a.balance_ << '\n'; }
int main()
{
Account a, b;
a.deposit(100);
a.withdraw(30);
b.deposit(70);
std::cout << a.balance() << ' ' << a.history().size() << ' ' << a.same_balance(b) << '\n';
try {
a.withdraw(500);
} catch (const std::runtime_error& e) {
std::cout << e.what() << '\n';
}
audit(a);
}
70 2 1
insufficient funds
audit 70
This code does not compile, on purpose.
class Account {
public:
long balance() const { return balance_; }
private:
long balance_ = 0;
};
int main()
{
Account a;
a.balance_ = 1000000; // 'balance_' is a private member of 'Account'
return 0;
}
- Verdict: native. A class has
public,protectedandprivatesections, and members of aclassare private by default. Access is per class, sosame_balancereads the balance of another account, and afrienddeclaration gives a function or another class access to the private members. A getter that returns aconstreference gives a read-only view without a copy. Access control is a compile-time check, not a protection of memory: code with a pointer can still reach the bytes. - The failing block writes the private member
balance_frommain, which the compiler rejects. The pimpl idiom, a pointer to a private implementation class, also hides the layout of the members, so that changes to them do not force callers to recompile.
import java.util.ArrayList;
import java.util.List;
final class Account { // final: no subclass can change the rules
private long balance; // only code in Account can name these fields
private final List<Long> history = new ArrayList<>();
void deposit(long amount) {
if (amount <= 0) throw new IllegalArgumentException("deposit must be positive");
history.add(amount);
balance += amount;
}
void withdraw(long amount) {
if (amount > balance) throw new IllegalStateException("insufficient funds");
history.add(-amount);
balance -= amount;
}
long balance() { return balance; }
List<Long> history() { return List.copyOf(history); } // an unmodifiable copy
boolean sameBalance(Account other) {
return balance == other.balance; // access is per class, not per object
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
a.deposit(100);
a.withdraw(30);
System.out.println(a.balance() + " " + a.history());
try {
a.history().add(1_000_000L);
} catch (UnsupportedOperationException e) {
System.out.println("history is read-only");
}
try {
a.withdraw(500);
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
Account b = new Account();
b.deposit(70);
System.out.println(a.sameBalance(b));
}
}
70 [100, -30]
history is read-only
insufficient funds
true
This code does not compile, on purpose.
class Account {
private long balance;
long balance() { return balance; }
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
a.balance = 1_000_000; // balance has private access in Account
System.out.println(a.balance());
}
}
This code runs but gives a wrong answer on purpose.
import java.util.Date;
final class Meeting {
private final Date start; // final reference, mutable object
Meeting(Date start) { this.start = start; } // keeps the caller's object
Date start() { return start; }
}
public class Main {
public static void main(String[] args) {
Date d = new Date(0);
Meeting m = new Meeting(d);
d.setTime(86_400_000L); // the caller changes its own Date ...
m.start().setTime(172_800_000L); // ... or the one the getter returns
System.out.println(m.start().getTime());
}
}
172800000
- Verdict: native. Java has four levels of access for members:
privatefor the class, no modifier for the package,protectedfor the package and subclasses, andpublic. Modules add a level above packages, because a module exports only the packages that it lists. Access is checked per class, not per object, sosameBalancecan read the balance of another account.List.copyOfreturns an unmodifiable list, so a getter can expose data without exposing the field. - The failing block assigns a private field from another class, which the compiler rejects. The wrong block shows that
private finalprotects only the reference: the constructor keeps the caller'sDate, and the getter returns the same object, so outside code changes the meeting through both. Copy mutable values when they come in and when they go out, or use immutable types such asjava.time.Instant.
#include <stdio.h>
#include <stdlib.h>
/* The "header": callers see an incomplete type and functions, not the fields. */
struct account;
struct account *account_new(void);
int account_deposit(struct account *a, long amount);
int account_withdraw(struct account *a, long amount);
long account_balance(const struct account *a);
void account_free(struct account *a);
int main(void)
{
struct account *a = account_new();
account_deposit(a, 100);
account_withdraw(a, 30);
int refused = account_withdraw(a, 500);
printf("%ld %d\n", account_balance(a), refused);
account_free(a);
return 0;
}
/* The "implementation": in a real program, a separate .c file. */
struct account {
long balance;
};
struct account *account_new(void) { return calloc(1, sizeof(struct account)); }
int account_deposit(struct account *a, long amount)
{
if (amount <= 0)
return -1;
a->balance += amount;
return 0;
}
int account_withdraw(struct account *a, long amount)
{
if (amount > a->balance)
return -1;
a->balance -= amount;
return 0;
}
long account_balance(const struct account *a) { return a->balance; }
void account_free(struct account *a) { free(a); }
70 -1
This code does not compile, on purpose.
#include <stdio.h>
struct account; /* incomplete: the fields are not visible here */
struct account *account_new(void);
int main(void)
{
struct account *a = account_new();
a->balance = 1000000; /* the compiler does not know the layout */
return 0;
}
- Verdict: idiom. C has no access control on struct members. The opaque pointer idiom gives the same effect: the header declares
struct accountwithout its members, and functions that take a pointer to it. Code that includes only the header cannot read or write the fields, because it does not know the layout, and it cannot create anaccounton the stack, so a constructor function allocates it. TheFILEtype of the standard library works this way. Functions markedstaticare private to their source file. - The failing block, which sees only the declaration, tries to write a field through the pointer, and the compiler rejects it because the type is incomplete.
var a = new Account("ana");
a.Deposit(100);
a.Withdraw(30);
Console.WriteLine($"{a.Owner} {a.Balance} [{string.Join(", ", a.History)}]");
try
{
a.Withdraw(500);
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine(a.History is List<long>); // the caller sees only IReadOnlyList
sealed class Account(string owner)
{
private readonly List<long> history = [];
public string Owner { get; } = owner; // read-only after construction
public long Balance { get; private set; } // public get, private set
public IReadOnlyList<long> History => history.AsReadOnly();
public void Deposit(long amount)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
history.Add(amount);
Balance += amount;
}
public void Withdraw(long amount)
{
if (amount > Balance) throw new InvalidOperationException("insufficient funds");
history.Add(-amount);
Balance -= amount;
}
}
ana 70 [100, -30]
insufficient funds
False
This code does not compile, on purpose.
var a = new Account();
a.Balance = 1_000_000; // the set accessor is private
Console.WriteLine(a.Balance);
class Account
{
public long Balance { get; private set; }
}
- Verdict: native. C# has
private,protected,internal,protected internal,private protectedandpublicaccess for members, andfilefor types, and each accessor of a property can have its own level, as in{ get; private set; }. A property with onlygetcan be set only in the constructor or an initializer.AsReadOnlywraps a list in a view that has no methods to change it, so the caller cannot even cast it back toList<long>. - The failing block assigns
Balancefrom outside the class. The property is public, but its set accessor is private, so the compiler rejects the assignment with error CS0272.
"use strict";
class Account {
#balance = 0; // a private field: only code inside the class body can name it
#history = [];
deposit(amount) {
if (amount <= 0) throw new RangeError("deposit must be positive");
this.#history.push(amount);
this.#balance += amount;
}
get balance() { return this.#balance; } // read-only from outside
static isAccount(x) { return #balance in x; } // a brand check
}
const a = new Account();
a.deposit(100);
try {
a.balance = 5; // a getter with no setter: a TypeError in strict code
} catch (err) {
console.log(err.constructor.name);
}
console.log(a.balance, Object.keys(a), JSON.stringify(a));
console.log(Account.isAccount(a), Account.isAccount({ balance: 1 }));
function makeCounter() { // privacy by closure, the older idiom
let count = 0;
return { increment: () => ++count };
}
const c = makeCounter();
c.increment();
console.log(c.increment(), c.count);
TypeError
100 [] {}
true false
2 undefined
This code raises SyntaxError, on purpose.
class Account {
#balance = 0;
}
const a = new Account();
console.log(a.#balance); // private names are checked when the code is parsed
- Verdict: native. Class fields and methods whose names start with
#are private: only code in the class body can name them, and the engine enforces this. Private fields do not appear inObject.keys, inJSON.stringifyor through any form of reflection. The test#balance in xchecks whether an object was made by the class. A getter with no setter makes a property read-only, and assignment to it throws aTypeErrorin strict code. Closures are the older way to hide state, and still a common one. - The failing block reads
a.#balanceoutside the class. The check happens when the engine parses the file, so the program fails with aSyntaxErrorbefore any line runs.
package main
import (
"errors"
"fmt"
"slices"
)
// Account is exported; its fields are not, so other packages
// can change them only through the methods.
type Account struct {
balance int64
history []int64
}
func NewAccount() *Account { return &Account{} }
func (a *Account) Deposit(amount int64) error {
if amount <= 0 {
return errors.New("deposit must be positive")
}
a.history = append(a.history, amount)
a.balance += amount
return nil
}
func (a *Account) Withdraw(amount int64) error {
if amount > a.balance {
return errors.New("insufficient funds")
}
a.history = append(a.history, -amount)
a.balance -= amount
return nil
}
func (a *Account) Balance() int64 { return a.balance }
// History returns a copy, so callers cannot change the account's slice.
func (a *Account) History() []int64 { return slices.Clone(a.history) }
func main() {
a := NewAccount()
a.Deposit(100)
a.Withdraw(30)
h := a.History()
h[0] = 1_000_000
fmt.Println(a.Balance(), a.History(), a.Withdraw(500))
}
70 [100 -30] insufficient funds
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
type Stack struct {
items []int
}
func (s *Stack) Push(x int) { s.items = append(s.items, x) }
// Items returns the internal slice: the caller shares its backing array.
func (s *Stack) Items() []int { return s.items }
func main() {
var s Stack
s.Push(1)
s.Push(2)
view := s.Items()
view[0] = 99 // writes into the stack's own array
fmt.Println(s.Items())
}
[99 2]
- Verdict: native. Go controls access by package, not by type. A name that starts with an upper case letter is exported from its package, and every other name is visible only inside the package. A type usually has unexported fields, a constructor function such as
NewAccount, and exported methods. Inside one package, all code can read and write the fields, so the example, which is one file in packagemain, shows the shape of the code but not the check, which applies only to other packages. - The wrong block returns the internal slice. A slice is a view of an array, so the caller's
viewand the stack share one array, and the write toview[0]changes the stack. Returnslices.Clone(s.items), asHistoryin the run block does.
mod bank {
pub struct Account {
balance: i64, // private: only code in mod bank can name it
history: Vec<i64>,
}
impl Account {
pub fn new() -> Self {
Account { balance: 0, history: Vec::new() }
}
pub fn deposit(&mut self, amount: i64) -> Result<(), &'static str> {
if amount <= 0 {
return Err("deposit must be positive");
}
self.history.push(amount);
self.balance += amount;
Ok(())
}
pub fn withdraw(&mut self, amount: i64) -> Result<(), &'static str> {
if amount > self.balance {
return Err("insufficient funds");
}
self.history.push(-amount);
self.balance -= amount;
Ok(())
}
pub fn balance(&self) -> i64 {
self.balance
}
pub fn history(&self) -> &[i64] {
&self.history // a shared borrow: the caller can read, not change
}
}
}
fn main() {
let mut a = bank::Account::new();
a.deposit(100).unwrap();
a.withdraw(30).unwrap();
let refused = a.withdraw(500);
println!("{} {:?} {:?}", a.balance(), a.history(), refused);
}
70 [100, -30] Err("insufficient funds")
This code does not compile, on purpose. The error is E0616.
mod bank {
pub struct Account {
balance: i64,
}
impl Account {
pub fn new() -> Self {
Account { balance: 0 }
}
}
}
fn main() {
let mut a = bank::Account::new();
a.balance = 1_000_000; // outside mod bank
}
- Verdict: native. Items and fields are private by default, and
pubmakes them visible outside their module. Privacy is per module: the code ofmod bankcan use the fields ofAccount, and code outside it cannot, so outside code cannot build anAccountwith a struct literal either and must callnew.pub(crate)andpub(super)give levels in between. A method that returns&[i64]lends a read-only view, and the borrow checker stops the caller from changing the account while that view is alive. - The failing block assigns the private field
balancefrommain, outside the module, and the compiler reports error E0616.
Variations and related ideas
- Information hiding. The wider principle that each module hides a design decision behind its interface, of which encapsulation in classes is one form.
- Modules and packages. Go, Rust, Java modules and ES modules hide whole groups of types and functions, not only fields.
- Abstract data types. A type known only through its operations, as in the opaque types of ML modules, Ada private types and C's opaque pointers.
- Closures. Variables captured by a function are unreachable from outside, which makes closures a complete form of encapsulation. See closures.
- Immutability. An immutable object needs no guard on its fields after construction, because nothing can change them. See immutability.
- Interfaces. A type that has only abstract operations is the most complete separation of interface from implementation. See interfaces.
- Capabilities. In object-capability systems, a reference to an object is the permission to use it, so encapsulation becomes a security boundary.
Pitfalls
- Leaking internal references. Returning a mutable field, or storing a mutable argument without copying it, gives outside code a way around the methods. Copy, wrap in a read-only view, or use immutable types.
- Getters and setters for every field. Public accessors that do nothing but read and write the field expose the representation as much as a public field does. Design the operations from what callers need.
- Protected fields. A field visible to subclasses is part of the interface for every subclass, written by people who may not know the invariant. Prefer private fields with protected methods. See class inheritance.
- Privacy is not security. Reflection in Java and C#, pointer arithmetic in C and C++, and the mangled names of Python can all reach private data. Access control organizes code; it does not protect secrets from code in the same process.
- Invariants broken during a method. An exception thrown half way through an update can leave the object in a state that breaks its invariant. Check before changing anything, or change a copy and swap it in.
- Encapsulating too much. A wrapper that hides a plain record behind methods adds code without protecting any rule. Data with no invariant can be a plain public record.
Cost
Access control costs nothing at run time in compiled languages: the compiler checks it and generates the same code as for a public field. A small getter is inlined by C++, Rust, Java and C# compilers, so it costs no more than reading the field. Private # fields in JavaScript engines are as fast as ordinary properties. Opaque pointers in C force allocation on the heap and an indirect call through the library for every operation, which inlining across files can remove. Defensive copies cost time and memory in proportion to the size of what they copy, and read-only views avoid that cost.
History
David Parnas argued in 1972 that a program should be split into modules that each hide a design decision, which became the principle of information hiding. Simula 67 had classes but no access control; later versions of Simula added hidden and protected. Smalltalk, from the 1970s, made instance variables visible only to the object's own methods. Barbara Liskov's CLU, from 1974, and Ada, from 1980, gave abstract data types whose representation only the type's own operations could see.
C with Classes had public and private from 1980, C++ added protected in 1987, and Java and C# kept all three in the 1990s. Go, released in 2009, chose package-level visibility marked by the case of a name, and Rust made privacy the default for every item and field.2 JavaScript had only closures for private state until ECMAScript 2022 added # private fields and methods.4
References
- Controlling Access to Members of a Class, The Java Tutorials, The opening paragraph
- Visibility and privacy, The Rust Reference, The opening rules
- The Go Programming Language Specification, Exported identifiers
- Private elements, MDN Web Docs, Description
- The Python Tutorial, Classes, 9.6 Private Variables
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 6Q423K Edit this page History Report an error Markdown