Описание тега accessor

An Accessor is (usually) a function that is responsible for reading or writing a property.

Overview

It's a common practice in OOP to make the properties of a class unaccessible from outside.

To provide a way to operate the data in those properties, accessors are made. Typically, two accessors are provided for a property, one for getting the value, and one for setting it. However, the real advantage of accessors is that they can perform some additional computation before the data is actually set or read. For example, if one has a class for dividing numbers, an accessor can prevent setting the divisor property to zero, and act accordingly.

A typical pair of accessors (in C++) (note how we can put checks into the accessors):

class MyClass
{
public:
    void set( int newValue );
    int & get( void );
private:
    int property;
}

void MyClass::set( int newValue )
{
   //we can utilize the accessor to check the value before actually storing it.
   if( newValue > 0 )
       property = newValue;
   else
       return;
}

int & MyClass::get()
{
    return property;
}

See also