Field encapsulation
In computer programming, field encapsulation involves using methods to access or modify a field rather than interacting with it directly. These accessor methods, commonly named getX and setX (where X represents the field's identifier), are typically declared as public, whereas the actual field remains private. This design limits direct manipulation of the data, thereby improving control and safeguarding integrity.
Consider this Java class example with a publicly accessible name field:
<syntaxhighlight lang="java"> public class NormalFieldClass {
public String name;
public static void main(String[] args)
{
NormalFieldClass example1 = new NormalFieldClass();
example1.name = "myName";
System.out.println("My name is " + example1.name);
}
} </syntaxhighlight>
Now compare it to an encapsulated approach:
<syntaxhighlight lang="java"> public class EncapsulatedFieldClass {
private String name;
public String getName()
{
return name;
}
public void setName(String newName)
{
name = newName;
}
public static void main(String[] args)
{
EncapsulatedFieldClass example1 = new EncapsulatedFieldClass();
example1.setName("myName");
System.out.println("My name is " + example1.getName());
}
} </syntaxhighlight>
In the initial example, the name variable is openly accessible and modifiable. Conversely, in the encapsulated version, access to the private field is mediated through getName and setName, enabling the class author to regulate how the data is handled.
Advantages
- The internal representation of data remains concealed; for example, imposing character restrictions can facilitate data validation or compression within the set method.
- Accessor methods may exist in two forms: one optimized for performance under valid input assumptions, and another incorporating validation checks useful during debugging or development phases.
- Modifications to data storage mechanisms can be made without impacting external code that relies on the class, thereby minimizing unintended consequences. This approach is especially beneficial in operating system development environments where application code and OS internals are maintained separately.
Disadvantages
Calling accessor functions introduces additional overhead compared to direct field manipulation. While this performance cost is less significant with modern high-speed processors, it remains a consideration in real-time systems and on slower embedded hardware. In languages such as C++, getter and setter functions are often implemented as inline methods, which reduces overhead by making them behave similarly to direct field access when inlined.