Why do object-oriented programming languages require manually-written getter functions?

30 Views Asked by At

This is a question of why programming languages are designed as they are.

Object-oriented programming languages often allow class member variables to be declared with keywords like private and protected, which stops functions outside the class (or derived classes or the module in the case of protected in D) from having access to those variable. I understand the purpose of this to be to prevent unexpected behaviour; so that the variables can't be rewritten because of mistakes in other files, or in the case of larger multi-person projects, one person can't insert some code somewhere that alters the variable without others knowing.

This means that when there's a need for member variables to be readable outside the class, but not writable, it's often advised to make the variables protected or private, and then add a getter function to access them.

Here is an example of how it may be written in D, though this practice would look similar in other object-oriented languages:

class someClass
{
    protected int someValue;

    this(int someValue) {
        this.someValue = someValue
    }

    int getSomeValue() {
        return this.someValue
}

And here's a function outside someClass that needs to obtain the value of someValue:

void outsideFunctionSomewhereElse (someClass[] manyObjects) {
    foreach (someObject; manyObjects) {
        int thisValue = someObject.getSomeValue();
        //More things may happen here.
    }
    //More may happen here.
}

Given how common this practice is, why don't programming languages just make it easier and cleaner-looking by providing a read-only keyword, and not requiring the programmer to write the getter function themselves? That way, functions outside the class can read the values of the member variable using the same syntax as if it were a public member, but they won't be allowed to reassign the value.

If they did allow this, then the example above may be simplified to this:

class someClass
{
    writeprotected int someValue;

    this(int someValue) {
        this.someValue = someValue
    }
}

And the function outside the class accessing someClass.someValue:

void outsideFunctionSomewhereElse (someClass[] manyObjects) {
    foreach (someObject; manyObjects) {
        int thisValue = someObject.someValue;
        //More may happen here.
    }
    //More may happen here.
}

Given how easy it is to think of this idea, I imagine there must be a reason why object-oriented languages don't already have this feature. What is that reason?

0

There are 0 best solutions below