Getter and setter

Also known as: accessor and mutator methods

On this page 8

A getter and setter pair is a set of two methods that read and write a single property of an object while the underlying field stays hidden. In object-oriented programming, the getter (also called an accessor) returns the current value, and the setter (a mutator) assigns a new one, usually after checking it. Together, these accessor and mutator methods turn direct field access into a controlled interface, which is the most common practical expression of encapsulation.

The idea is simple, but its use is debated. Used well, getters and setters protect class invariants, allow lazy computation and keep a public API stable while the internal representation changes. Used mechanically, they add boilerplate around every field and expose internal state almost as openly as public fields would.

How accessor and mutator methods work

A getter and setter work by placing a method call between the caller and the stored value. The field is declared with a restrictive access modifier, typically private, so code outside the class cannot touch it. The class then exposes getBalance() to read the value and setBalance(amount) to change it, and every access passes through code the class controls.

That indirection is the whole point. Inside the setter, the class can reject invalid input, normalize a value, notify observers or record an audit entry. Inside the getter, it can return a defensive copy of a mutable object, compute the value on demand or convert units. Callers see the same signature regardless of what happens inside.

The table below shows the typical responsibilities of each half of the pair.

MethodTypical nameMain responsibilitiesReturn value
GettergetName(), isActive()Read, compute, convert, copyThe property value
SettersetName(value)Validate, normalize, store, notifyUsually void or this
Boolean getterisEnabled(), hasItems()Read a true or false stateBoolean
Fluent setterwithName(value)Store and allow chainingThe object itself
Responsibilities of getters and setters

Getter and setter syntax across languages

Languages implement getters and setters either as explicit methods or as language-level properties. Java relies on naming conventions defined by the JavaBeans specification, where a field name gets getName() and setName(), and frameworks discover them by reflection. C#, Python, Kotlin, Swift and JavaScript offer property syntax, so the caller writes account.balance = 50 while the runtime silently invokes the setter.

Property syntax matters because it removes the main migration cost. A public field can later become a property with validation without changing any calling code, which weakens the classic argument for writing accessors in advance.

LanguageMechanismCaller syntaxNotes
JavaMethods by conventionobj.getX(), obj.setX(v)Records provide read-only accessors
C#Properties with get and setobj.X = vAuto-properties generate the field
PythonThe @property decoratorobj.x = vPlain attributes are idiomatic first
KotlinProperties with custom accessorsobj.x = vval is read-only, var is mutable
JavaScriptget and set keywordsobj.x = vPrivate fields use the # prefix
C++Ordinary member functionsobj.x(), obj.setX(v)No built-in property syntax
Accessor mechanisms in common languages

Why getters and setters support encapsulation

Getters and setters support encapsulation by letting a class change its internal representation without breaking callers. A Temperature class may store Kelvin internally and still offer getCelsius(); a later switch to a different storage format affects only the accessor bodies. This is the uniform access principle: callers should not need to know whether a value is stored or computed.

The setter is also the natural place to enforce invariants, the conditions that must always hold for an object to be valid. A percentage must stay between 0 and 100, an end date must not precede a start date, and a collection reference must never be null. If every write goes through the setter, the invariant is checked in exactly one place.

Accessors also enable read-only and write-only exposure. Omitting the setter, or giving it a narrower access modifier than the getter, lets outside code observe a value that only the class itself may change.

Getters and setters are one of several ways to expose object state, and each alternative trades flexibility against simplicity. The comparison below places them next to the most frequent alternatives in object-oriented design.

ApproachValidation possibleRepresentation hiddenBest fit
Public fieldNoNoSimple data carriers, internal structs
Getter and setterYesPartlyMutable state with rules
Getter onlyAt constructionPartlyImmutable value objects
Behavioral methodYesFullyDomain logic such as deposit()
Constructor injectionYesFullyRequired, unchanging dependencies
Ways to expose object state

The strongest alternative is the behavioral method. Instead of setBalance(getBalance() - amount), a well-designed account offers withdraw(amount), which keeps the rule about overdrafts inside the object. This follows the guideline often summarized as tell, do not ask: callers state intent rather than pulling data out, modifying it and pushing it back.

Common mistakes with getters and setters

Most problems with getters and setters come from generating them automatically for every field. An IDE can produce a full set in seconds, but a class whose fields all have public accessors offers encapsulation in name only, because any caller can still read and replace any value. Such classes are often called anemic domain models: they hold data while the logic that governs it is scattered across services.

MistakeConsequenceBetter practice
Accessors for every fieldInternal state fully exposedExpose only what callers need
Setter without validationInvalid objects can existCheck rules or remove the setter
Getter returns a mutable listCallers modify hidden stateReturn a copy or unmodifiable view
Heavy work in a getterSurprising latency and side effectsUse an explicit compute method
Setters on identity fieldsBroken hash-based collectionsMake identity fields final
Typical mistakes and their fixes

Getters should be free of observable side effects and cheap to call, because developers and debuggers invoke them freely. Setters on fields used in equals() and hashCode() are particularly dangerous: changing such a value after inserting the object into a HashSet makes the element effectively unreachable.

Thread safety is another trap. A getter and setter pair does not make compound operations atomic, so a read followed by a write from two threads can lose an update unless the class uses synchronization or atomic types.

When to write getters and setters

Write getters and setters when a value must be readable or changeable from outside and the class needs some control over that access. Frameworks add a practical reason: many serialization libraries, object-relational mappers and UI data-binding systems expect accessor methods or properties to read and populate objects.

  • Prefer immutable objects with getters only when the state does not need to change after construction.
  • Use a behavioral method when a change follows a business rule rather than a plain assignment.
  • Keep a setter when external configuration or binding genuinely needs to replace the value.
  • In languages with property syntax, start with a plain property and add accessor logic only when it is needed.

Put simply

Think of an object as a bank vault and its fields as the money inside. Nobody walks into the vault directly. Instead, there is a teller window: the getter is the window where you ask what is inside, and the setter is the window where you hand something in.

Because the teller stands in between, the bank can count the bills, refuse a forged note or write down every transaction. If the bank later rearranges the vault, customers do not notice, because they still use the same window. The key takeaway is that getters and setters let an object stay in charge of its own data, as long as they are not added automatically to every field.

In practice

A development team builds a booking system for a chain of fitness studios. The ClassSession class stores a capacity and a list of booked members. An early version gave both fields public getters and setters, and a reporting script accidentally called setCapacity(0) on live sessions, which silently canceled bookings for about 40 customers.

During refactoring, the team removed the capacity setter and replaced it with resize(newCapacity), which rejects values below the current number of bookings. The getter for the member list now returns an unmodifiable view, and new bookings go through book(member), which checks capacity first. The result was that every rule about sessions lived in one class, and the same class of incident did not recur in the following release cycles.