Why don't oop languages โ€‹โ€‹support separate read and write access modifiers?

I often find that I write getters and setters just because it takes a different level of access to get and set up. And these getters and setters are trivial (getter only returns, setter sets only the value, another code inside). A typical case is when you want the field value to be read only for the outside world (and you write a whole bunch of getter functions for each field.)

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

Well, compilers can optimize function calls and inline assignments, but this is something you cannot control. Even the inline keyword in C ++ is just a hint, and compilers can ignore it. You must assume that the function is being called and it will be slower.

Also, languages โ€‹โ€‹(like C #, for example) never support properties and mimic this thing, but they are nothing but functions that look like a field, you can't even say it's a funciton or field (without the help of the IDE) .

What problems will arise if we can set different access modifiers for writing and reading (for example, as file systems), except how simple it is to say that this violates the dogmatic principle of encapsulation?

+4
source share
1 answer

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

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

The first creates the Foo property with a public recipient and a secure network device, and the second creates the Bar property with a secure getter and private setter.

As for Objective-C, the language is special for the general case ("public" getter, "private" setter), allowing you to declare a readonly property and then update its readwrite in a class extension or subclass.

What other languages โ€‹โ€‹do you mean?

+5
source

All Articles