Conceptintro
Field and property
Also called field, property, data member, instance variable, attribute, member variable, computed property, backing field, accessor, getter and setter, auto-property, stored property.
A field is a variable stored in each object. A property looks like a field to the code that uses it, but reads and writes run accessor code, which can check, compute or log the value.
- Applies to
- core-languages
Idea
A field is a variable that each object stores: a rectangle has a width field and a height field, and each rectangle holds its own values. A property is a member that the calling code reads and assigns like a field, but each read or assignment runs a function, an accessor. The function can return a stored value, compute a value, check a value before it stores it, or record the change. The value that a property stores is held in a field, its backing field. Python, C#, Kotlin, Swift and JavaScript have properties. Java, C++, Go and Rust have only fields, and code writes accessor methods by hand:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius # this assignment goes through the setter
@property
def celsius(self): # a property: code runs on each read
return self._celsius # the backing field
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
@property
def fahrenheit(self): # a computed property: no storage of its own
return self._celsius * 9 / 5 + 32
t = Temperature(20)
print(t.celsius, t.fahrenheit)
t.celsius = 30 # reads like a field assignment
print(t.celsius, t.fahrenheit)
try:
t.celsius = -300
except ValueError as e:
print("ValueError:", e)
print(vars(t)) # the instance stores only the backing field
20 68.0
30 86.0
ValueError: below absolute zero
{'_celsius': 30}
celsius is a property with a check, and _celsius is its backing field. fahrenheit is a computed property: it has no storage and is computed from _celsius on each read. The calling code uses t.celsius and t.fahrenheit as if they were fields, and vars(t) shows that the instance stores one value.
How it works
A field is storage in the object. The JLS states it for Java: "The variables of a class are introduced by field declarations."1 Go describes a struct in the same terms: "A struct is a sequence of named elements, called fields, each of which has a name and a type."2 A field read is a load from a fixed offset in the object, and a field write is a store, with no code of the class in between. A field can be an instance field, with one value in each object, or a static field, with one value for the class. C++ calls fields data members, and Python calls them attributes.
A property runs code on access. Wikipedia describes a property as "a special sort of class member, intermediate in functionality between a field (or data member) and a method".3 The C# guide gives the purpose: "A property is a member that provides a flexible mechanism to read, write, or compute the value of a data field."4 The compiler, or the runtime in Python and JavaScript, turns t.celsius into a call of the getter and t.celsius = 30 into a call of the setter. In JavaScript, "The get syntax binds an object property to a function that will be called when that property is looked up."5 In Python, "Calling property() is a succinct way of building a data descriptor that triggers a function call upon access to an attribute."6
Stored and computed properties. Swift names the two kinds: "Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value."7 A computed property, such as an area or a full name, has a getter and often no setter, and it never gets out of date, because nothing stores it.
Backing fields. A stored property needs a field to hold the value. C# and Kotlin generate it when the accessors are the default ones. For a C# auto-implemented property, "The compiler generates a hidden backing field for the property."4 Kotlin does the same: "The compiler automatically generates backing fields for properties when a value needs to be stored in memory", and a custom accessor reaches the generated field with the keyword field.8 C# 14 adds the same keyword: "The field keyword accesses the compiler synthesized backing field for a property."4 Without such a keyword, the code declares the backing field by hand, often with a name such as _celsius.
Uniform access. Because a property and a field look the same to the calling code, a class can start with a public field and change it to a property later, when it needs a check or a computed value, without changes to the code that uses it. This holds at the source level in Python, JavaScript, Kotlin and Swift. In C# it does not hold for compiled code: a field and a property compile to different instructions, so the change breaks binary compatibility, and C# code makes public members properties from the start. In Java, C++, Go and Rust, a field and a method call have different syntax, so code that may need a check later hides the field behind accessor methods from the start. See encapsulation and visibility.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Idiom | Struct members are fields, and functions that take a pointer to the struct play the part of accessors. |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript, with typed fields, readonly fields that the compiler checks, access modifiers and parameter properties; no example file because it would repeat the JavaScript one. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Native | Every val and var member is a property with a generated getter and setter, and custom accessors reach the backing field with the field keyword; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Idiom | A column of a table is a field of each row, and generated columns are computed from other columns. |
| Bash | Does not apply | Bash has variables and arrays but no objects with fields. |
| PowerShell | Native | Classes declare properties, and Add-Member adds note and script properties to objects; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Idiom | Element attributes hold values, and the DOM exposes them as properties of element objects in JavaScript. |
| CSS | Idiom | CSS properties set the style of elements, which is a different idea; custom properties hold values that other declarations read. |
| Regular expressions | Does not apply | A pattern has no data members. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | attributes as fields; @property with a getter, a setter and a deleter; __slots__ |
| JavaScript | native | public and #private fields; get and set accessors |
| TypeScript | native | as JavaScript, with typed fields, readonly and access modifiers |
| Java | idiom | fields; getX and setX methods; record accessors |
| Kotlin | native | every val and var member is a property; field in custom accessors |
| C# | native | fields; properties with get, set and init; auto-implemented properties |
| Go | idiom | struct fields; exported names; getter methods without a Get prefix |
| Rust | idiom | struct fields; pub for visibility; accessor methods |
| C | idiom | struct members; functions that read and write them |
| C++ | idiom | data members; accessor member functions |
| Bash | n/a | variables only |
| PowerShell | native | class properties; Add-Member script properties |
| SQL | idiom | columns of a table; computed or generated columns |
| Regex | n/a | no data members |
| HTML | idiom | attributes of elements, and DOM properties that reflect them |
| CSS | idiom | properties that style elements, a different idea; custom properties |
The languages differ in whether property syntax exists and in what a field declaration means. In Kotlin and Swift every member variable is a property, and the compiler adds the field only when needed. In C#, fields and properties are separate kinds of member. In Python and JavaScript, an instance can gain fields at run time by assignment, while a property is defined once, on the class or the prototype. Java, C++, Go and Rust have only fields, and code that needs a check writes methods.
Each example file defines a rectangle with a width, a height and an area, makes area a computed value, and checks the width where the language allows it.
class Rectangle:
__slots__ = ("width", "height") # the only fields an instance can have
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
r = Rectangle(3, 4)
print(r.width, r.area)
r.width = 5
print(r.area)
print(type(Rectangle.__dict__["area"]).__name__)
try:
r.area = 1 # a property without a setter cannot be assigned
except AttributeError:
print("AttributeError: area")
try:
r.depth = 2 # __slots__ allows no other fields
except AttributeError:
print("AttributeError: depth")
3 12
20
property
AttributeError: area
AttributeError: depth
- Verdict: native. A field is an attribute that an instance stores, and
self.width = widthcreates it. A property is an object of the typepropertythat lives in the class and runs a function on each read, sor.areahas no parentheses and always gives the current area. - A property without a setter is read-only.
__slots__replaces the attribute dictionary of each instance with fixed storage, which saves memory and stops typing mistakes such asr.widht = 5from creating a field. - A field can become a property later without a change to the code that uses it, so Python code starts with plain fields.
#include <iostream>
#include <stdexcept>
struct Size {
int width = 0; // public data members with default member initializers
int height = 0;
};
class Rectangle {
public:
Rectangle(int width, int height) : height_(height) { set_width(width); }
int width() const { return width_; } // an accessor
void set_width(int width) {
if (width < 0) {
throw std::invalid_argument("negative width");
}
width_ = width;
}
int area() const { return width_ * height_; } // computed on each call
private:
int width_ = 0; // private data members
int height_ = 0;
};
int main() {
Size s{3, 4};
s.width = 5; // any code can change a public member
std::cout << s.width << ' ' << s.height << '\n';
Rectangle r(3, 4);
std::cout << r.width() << ' ' << r.area() << '\n';
r.set_width(5);
std::cout << r.area() << '\n';
try {
r.set_width(-1);
} catch (const std::invalid_argument &e) {
std::cout << e.what() << '\n';
}
std::cout << sizeof(Rectangle) << ' ' << sizeof(Size) << '\n';
}
5 4
3 12
20
negative width
8 8
- Verdict: idiom. C++ calls fields data members and has no property syntax. A plain aggregate such as
Sizeuses public members, and a class with an invariant keeps them private and adds accessor functions. - The accessors are ordinary member functions. A short accessor defined in the class body is inline, so it usually costs nothing after optimization.
- The accessors add no storage:
RectangleandSizeboth hold twointvalues.
public class Main {
static final class Rectangle {
private int width; // fields are private
private int height;
Rectangle(int width, int height) {
setWidth(width);
this.height = height;
}
int getWidth() { // a getter
return width;
}
void setWidth(int width) { // a setter with a check
if (width < 0) {
throw new IllegalArgumentException("negative width");
}
this.width = width;
}
int getArea() { // a computed value, with no field
return width * height;
}
}
record Size(int width, int height) {} // a record: final fields and accessors
public static void main(String[] args) {
Rectangle r = new Rectangle(3, 4);
System.out.println(r.getWidth() + " " + r.getArea());
r.setWidth(5);
System.out.println(r.getArea());
try {
r.setWidth(-1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
Size s = new Size(3, 4);
System.out.println(s.width() + " " + s);
}
}
3 12
20
negative width
3 Size[width=3, height=4]
- Verdict: idiom. Java has fields and no property syntax. The convention from JavaBeans is a private field with public methods
getWidthandsetWidth, and tools such as serializers find properties by these names. - A computed property is a method with no field behind it, such as
getArea. - A record declares its fields in the header and gets one accessor method for each, named like the field:
s.width(), nots.getWidth(). The fields are final, so a record has no setters.
using System;
var r = new Rectangle(3, 4) { Name = "door" };
Console.WriteLine($"{r.Width} {r.Area} {r.Name}");
r.Width = 5;
Console.WriteLine(r.Area);
try
{
r.Width = -1;
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("ArgumentOutOfRangeException");
}
class Rectangle
{
private int width; // the backing field of Width
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
public int Width
{
get => width;
set
{
ArgumentOutOfRangeException.ThrowIfNegative(value);
width = value;
}
}
public int Height { get; set; } // an auto-implemented property
public string Name { get; init; } = ""; // set only during initialization
public int Area => Width * Height; // a computed, read-only property
}
3 12 door
20
ArgumentOutOfRangeException
- Verdict: native. A property has a
getaccessor, asetorinitaccessor, or both. Code reads and assigns it like a field, and the compiler turns each use into a call of the accessor. Height { get; set; }is an auto-implemented property: the compiler makes a hidden backing field.Widthhas an explicit backing field because its setter checks the value.Areahas only an expression body, so it is computed on each read and cannot be assigned.initallows a value only in the constructor or in an object initializer, such as{ Name = "door" }.
"use strict";
class Rectangle {
#width; // a private field
height = 0; // a public field with an initial value
constructor(width, height) {
this.width = width; // goes through the setter
this.height = height;
}
get width() {
return this.#width;
}
set width(value) {
if (value < 0) throw new RangeError("negative width");
this.#width = value;
}
get area() {
return this.#width * this.height;
}
}
const r = new Rectangle(3, 4);
console.log(r.width, r.area);
r.width = 5;
console.log(r.area);
console.log(Object.keys(r)); // own fields only; the accessors are on the prototype
try {
r.width = -1;
} catch (e) {
console.log(e.name);
}
try {
r.area = 1; // a getter without a setter
} catch (e) {
console.log(e.name);
}
3 12
20
[ 'height' ]
RangeError
TypeError
- Verdict: native. A field declaration such as
height = 0gives each instance its own property.getandsetdefine an accessor property on the prototype, so a read or an assignment calls a function. - A field whose name starts with
#is private to the class body, and the accessors give controlled access to it.Object.keyslists onlyheight, because#widthis private and the accessors belong to the prototype. - Assigning to a property that has a getter and no setter throws a
TypeErrorin strict mode, which class bodies always use; outside strict mode the assignment is ignored without an error.
package main
import (
"errors"
"fmt"
)
// Size has exported fields: other packages read and write them directly.
type Size struct {
Width, Height int
}
// Rectangle hides its fields; the lowercase names are visible only in the package.
type Rectangle struct {
width, height int
}
func (r *Rectangle) Width() int { return r.width } // a getter is named Width, not GetWidth
func (r *Rectangle) SetWidth(w int) error {
if w < 0 {
return errors.New("negative width")
}
r.width = w
return nil
}
func (r *Rectangle) Area() int { return r.width * r.height }
func main() {
s := Size{Width: 3, Height: 4}
s.Width = 5
fmt.Println(s.Width, s.Height)
r := &Rectangle{width: 3, height: 4}
fmt.Println(r.Width(), r.Area())
fmt.Println(r.SetWidth(5), r.Area())
fmt.Println(r.SetWidth(-1))
}
5 4
3 12
<nil> 20
negative width
- Verdict: idiom. Go has struct fields and no properties. A field whose name starts with an upper-case letter is exported, and a field with a lower-case name is visible only inside its package.
- Go code uses exported fields for plain data and methods for checked access. The convention names a getter after the field,
Width, without aGetprefix, and a setterSetWidth. - A setter that can fail returns an
error, because Go has no exceptions for this.
mod shapes {
pub struct Size {
pub width: u32, // public fields
pub height: u32,
}
pub struct Rectangle {
width: u32, // private to the module
height: u32,
}
impl Rectangle {
pub fn new(width: u32, height: u32) -> Self {
Rectangle { width, height }
}
pub fn width(&self) -> u32 {
self.width // a getter has the name of the field
}
pub fn set_width(&mut self, width: u32) {
self.width = width;
}
pub fn area(&self) -> u32 {
self.width * self.height
}
}
}
use shapes::{Rectangle, Size};
fn main() {
let mut s = Size { width: 3, height: 4 };
s.width = 5;
println!("{} {}", s.width, s.height);
let mut r = Rectangle::new(3, 4);
println!("{} {}", r.width(), r.area());
r.set_width(5);
println!("{}", r.area());
}
5 4
3 12
20
- Verdict: idiom. Rust has struct fields and no properties. A field is private to its module unless it is marked
pub, so code outsideshapescannot writer.widthand must call the methods. - A getter has the name of the field,
width(), and a setterset_width. A method with&selfreads, and one with&mut selfchanges the struct. - A type such as
u32can carry part of the check: a negative width cannot exist, soset_widthhas no check to make.
Variations and related ideas
- Read-only and init-only properties. A property with a getter only, a Kotlin
val, a C#initaccessor and a Java record component allow a value to be set once, at construction. See immutability. - Lazy properties. "A lazy stored property is a property whose initial value isn't calculated until the first time it's used."7 Kotlin has
by lazy, and Python hasfunctools.cached_property. - Property observers. Swift's
willSetanddidSetrun code before and after a stored property changes, and data binding in user interface frameworks uses notifications such asINotifyPropertyChangedin .NET. - Getters and setters. In languages without property syntax, a pair of methods plays the part of a property. Wikipedia notes that "Some object-oriented languages, such as Java and C++, do not support properties, requiring the programmer to define a pair of accessor and mutator methods instead."3
- Indexers. C# indexers and Python's
__getitem__let an object be read like an array, with the same idea of accessor code behind the syntax. - Static fields and properties. A field or property can belong to the class and have one value for all instances. See classes and instances.
Pitfalls
- A setter that calls itself. In a Python property named
celsius, the setter must store intoself._celsius, notself.celsius, or each assignment calls the setter again until the recursion limit. The same mistake in C# makes a setterset { Width = value; }recurse into a stack overflow. - Expensive or surprising getters. Code that reads a property expects a cheap read with no side effects. A getter that runs a query, allocates a large object or changes state belongs in a method with a name that says what it does.
- Public mutable fields. A public field lets any code break the invariants of the object, such as a negative width. Make it private and offer methods or a property with a check.
- A field and a property with the same data. A class that stores both the area and the sides can get them out of step. Compute the derived value in a property instead.
- Getters and setters for every field. A getter and a setter that pass every value through expose the representation as much as a public field does. Offer operations that keep the invariants of the class.
- Assigning to a read-only property. In JavaScript, assigning a property that has a getter and no setter throws a
TypeErrorin strict code and is ignored in sloppy code. The JavaScript example shows the error.
Cost
A field read or write is one memory access at a fixed offset. A property access is a function call, but compilers and JIT compilers inline small accessors in C#, Java, Kotlin, Swift, C++, Go and Rust, so a trivial getter usually costs the same as a field read. In Python, a property read calls a Python function, which costs more than a plain attribute read. Per object, a field costs its size plus any padding for alignment, a computed property costs no memory, and Python instances without __slots__ also pay for an attribute dictionary.
History
Simula 67 and Smalltalk objects held instance variables, and Smalltalk code read them from outside only through methods. Object Pascal in Delphi, released in 1995, declared properties with read and write accessors, and Anders Hejlsberg, the chief architect of Delphi, later led the design of C#, which made properties a basic kind of member. Python added property in version 2.2, together with descriptors, Kotlin and Swift made every member variable a property, and JavaScript added get and set in ECMAScript 5 and class fields in ECMAScript 2022.
References
- Chapter 8, Classes, The Java Language Specification, Java SE 25 Edition, 8.3 Field Declarations
- The Go Programming Language Specification, Struct types
- Property (programming), Wikipedia, Introduction; Support in languages
- Properties, C# programming guide, Introduction; Field backed properties; Auto-implemented properties
- get, MDN Web Docs, Description
- Descriptor Guide, Python HOWTOs, Properties; Managed attributes
- Properties, The Swift Programming Language, Stored Properties; Computed Properties; Lazy Stored Properties; Property Observers
- Properties, Kotlin documentation, Declaring properties; Backing fields
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 01BRCM Edit this page History Report an error Markdown