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.
| Method | Typical name | Main responsibilities | Return value |
|---|---|---|---|
| Getter | getName(), isActive() | Read, compute, convert, copy | The property value |
| Setter | setName(value) | Validate, normalize, store, notify | Usually void or this |
| Boolean getter | isEnabled(), hasItems() | Read a true or false state | Boolean |
| Fluent setter | withName(value) | Store and allow chaining | The object itself |
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.
| Language | Mechanism | Caller syntax | Notes |
|---|---|---|---|
| Java | Methods by convention | obj.getX(), obj.setX(v) | Records provide read-only accessors |
| C# | Properties with get and set | obj.X = v | Auto-properties generate the field |
| Python | The @property decorator | obj.x = v | Plain attributes are idiomatic first |
| Kotlin | Properties with custom accessors | obj.x = v | val is read-only, var is mutable |
| JavaScript | get and set keywords | obj.x = v | Private fields use the # prefix |
| C++ | Ordinary member functions | obj.x(), obj.setX(v) | No built-in property syntax |
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 compared with related approaches
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.
| Approach | Validation possible | Representation hidden | Best fit |
|---|---|---|---|
| Public field | No | No | Simple data carriers, internal structs |
| Getter and setter | Yes | Partly | Mutable state with rules |
| Getter only | At construction | Partly | Immutable value objects |
| Behavioral method | Yes | Fully | Domain logic such as deposit() |
| Constructor injection | Yes | Fully | Required, unchanging dependencies |
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.
| Mistake | Consequence | Better practice |
|---|---|---|
| Accessors for every field | Internal state fully exposed | Expose only what callers need |
| Setter without validation | Invalid objects can exist | Check rules or remove the setter |
| Getter returns a mutable list | Callers modify hidden state | Return a copy or unmodifiable view |
| Heavy work in a getter | Surprising latency and side effects | Use an explicit compute method |
| Setters on identity fields | Broken hash-based collections | Make identity fields final |
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.