An accessor is a type of method used in
object-oriented programming languages to return the value of an
data member. (Compare with mutator). Public accessor methods are a
best practice, recommended by many coding standards as the correct
way to access fields of a class, while the member itself can remain
private.
Some conventions even mandate that access within the class itself should
be through the accessor methods. This ensures that attempts to read the
instance variable are all performed at a single point in the code, which
can often be of assistance when debugging multi-threaded
applications.
The format of an accessor method is uncomplicated almost by definition.
For example, given a member variable "balance" of type double, the
corresponding accessor would be:
public double getBalance()
{
return balance;
}
While most accessors take no arguments, on occasion there is value
in an accessor that takles an index to return a single element of an
array or collection, rather than the entire collection itself.
Design patterns such as JavaBeans make use of this kind of
convention, and treat such accessors as an indexed property.
Accessors are by far the most important type of setter method.
However in many object-oriented languages such as Java, they do
present some issues when they are used to access member variables
that are themselves objects. The member is returned as a reference,
which may allow the caller to inadvertently modify it. This is
particularly an issue with collection classes. In other languages
such as C++ that support the notion of const, it is a good idea to
make an accessor a const method that returns a const reference.