encapsulation
object-oriented programming
accessors
data hiding
getter and setter methods

Property getters and setters

Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD

Property getters and setters are crucial concepts in object-oriented programming (OOP) that promote encapsulation by controlling access to an object's attributes. They enable the user to retrieve and update attribute values while maintaining the integrity and validation of those attributes.

Technical Explanation

Encapsulation

Encapsulation is a fundamental concept in OOP that involves bundling the data and methods that operate on the data within a single unit, typically a class, and restricting access to some of the object's components. This mechanism is primarily achieved using property getters and setters.

Property Getters

A getter is a method that allows the program to retrieve the value of a private attribute from outside the object. The getter method provides a controlled access mechanism to the attribute, allowing for additional logic, such as validation or formatting, to be applied when retrieving the value.

Property Setters

A setter is a method that allows updating the value of a private attribute from outside the object. The setter method provides a controlled access mechanism to set the attribute, enabling validation, logging, or triggering events when a property value is changed.

Advantages of Using Getters and Setters

  1. Encapsulation: Protects the internal state of an object by controlling how attributes are accessed and modified.
  2. Validation: Ensures that only valid data is assigned to attributes.
  3. Consistency: Maintains consistent internal state representation.
  4. Flexibility: Allows the implementation to change without affecting code that uses the class.

Example: Python Getters and Setters

In Python, the property decorator simplifies the creation of getters and setters. Consider the following example illustrating their usage:

python
1class Person:
2    def __init__(self, name, age):
3        self._name = name
4        self._age = age
5    
6    @property
7    def name(self):
8        return self._name
9    
10    @name.setter
11    def name(self, value):
12        if not isinstance(value, str):
13            raise ValueError("Name must be a string")
14        self._name = value
15    
16    @property
17    def age(self):
18        return self._age
19    
20    @age.setter
21    def age(self, value):
22        if not (0 <= value <= 120):
23            raise ValueError("Age must be between 0 and 120")
24        self._age = value
25
26# Usage
27p = Person("John", 30)
28print(p.name)  # Getter
29p.age = 35     # Setter

In this example, attempting to set the name to a non-string or age to an out-of-bound value results in a ValueError.

Table Summary

Here's a summary of key points about property getters and setters:

ConceptDescription
EncapsulationBundles data with methods to restrict direct access.
GetterRetrieves the value of a property with optional logic (e.g., validation).
SetterUpdates the property value with optional validation or additional logic.
AdvantagesProvides encapsulation, validation, consistency, and flexibility.
Example SyntaxPython example using the property decorator to define getters and setters.

Additional Details and Subtopics

Best Practices

  • Private Attributes: Use leading underscores to denote private attributes (e.g., _age).
  • Appropriate Use: Use getters/setters only when additional logic is necessary; avoid over-complicating simple attributes.
  • Performance: Though minor, consider performance implications when processing logic-heavy getters or setters.

Language-Specific Implementations

  • Java: Java has explicit get and set methods standardized by convention.
java
1  public class Person {
2      private String name;
3      private int age;
4      
5      public String getName() { return name; }
6      public void setName(String name) { this.name = name; }
7      
8      public int getAge() { return age; }
9      public void setAge(int age) { 
10          if (age < 0 || age > 120) throw new IllegalArgumentException("Invalid age");
11          this.age = age;
12      }
13  }
  • C#: C# uses properties directly with get/set blocks.
csharp
1  public class Person {
2      public string Name { get; set; }
3      private int _age;
4      
5      public int Age {
6          get { return _age; }
7          set {
8              if (value < 0 || value > 120)
9                  throw new ArgumentOutOfRangeException(nameof(value), "Invalid age");
10              _age = value;
11          }
12      }
13  }

Alternatives

While getters and setters are standard for encapsulation, some languages like JavaScript's ES6 offer alternatives such as proxy objects that can intercept and redefine how attributes are accessed or modified.

Understanding property getters and setters is essential for writing robust and maintainable object-oriented programs. They ensure that the internal state of an object remains consistent and valid, reflecting the core principles of encapsulation.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD

All Rights Reserved.