4

I often find myself writing getters and setters just because getting and setting would require different access level. And those getters and setters are trivial (getter only returns, setter only sets the value, no other code inside). Typical case when you want a field value to be read only for the outside world (and you write a whole bunch of getter functions for every field.)

Getters and setters are functions under the hood. And calling a function is slower than just setting a field, because you need to copy arguments, push and pop a stack frame, copy the result etc.

Well, compilers may optimize out the function call and inline the assignment, but this is a thing you can't control. Even inline keyword in c++ is only a hint and compilers are free to ignore it. You should assume that a function is called and it will be slower.

Moreover never languages (like C#) support properties and mimic this thing but they are nothing but functions that look like a field, you can't even tell that it's a funciton or a field (without the aid of the IDE).

What problems would arise if we could set different access modifiers for writing and reading (Like file systems do for example), other than just telling it would violate the dogmatic principle of encapsulation?

Calmarius
  • 18,570
  • 18
  • 110
  • 157

1 Answers1

5

But you can create properties with different access for the getter and setter in C#:

public int Foo {
    get { return foo; }
    protected set { foo = value; }
}

protected int Bar { get; private set; }

The first creates a property "Foo" with a public getter and a protected setter, while the second creates a property "Bar" with a protected getter and a private setter.

As for as Objective-C, the language specifically for the common case ("public" getter, "private" setter) by allowing you to declare a property readonly and then redeclare it readwrite in a class extension or subclass.

What other languages do you have in mind?

Anomie
  • 92,546
  • 13
  • 126
  • 145