Search code examples
oopprogramming-languages

Why don't oop languages have a 'read only' access modifier?


Every time I write trivial getters (get functions that just return the value of the member) I wonder why don't oop languages simply have a 'read only' access modifier that would allow reading the value of the members of the object but does not allow you to set them just like const things in c++.

The private,protected,public access modifiers gives you either full (read/write) access or no access.

Writing a getter and calling it every time is slow, because function calling is slower than just accessing a member. A good optimizer can optimize these getter calls out but this is 'magic'. And I don't think it is good idea learning how an optimizer of a certain compiler works and write code to exploit it.

So why do we need to write accessors, read only interfaces everywhere in practice when just a new access modifier would do the trick?

ps1: please don't tell things like 'It would break the encapsulation'. A public foo.getX() and a public but read only foo.x would do the same thing.

EDIT: I didn't composed my post clear. Sorry. I mean you can read the member's value outside but you can't set it. You can only set its value inside the class scope.


Solution

  • You're incorrectly generalizing from one or some OOP language(s) you know to OOP languages in general. Some examples of languages that implement read-only attributes:

    • C# (thanks, Darin and tonio)
    • Delphi (= Object Pascal)
    • Ruby
    • Scala
    • Objective-C (thanks, Rano)
    • ... more?

    Personally, I'm annoyed that Java doesn't have this (yet?). Having seen the feature in other languages makes boilerplate writing in Java seem tiresome.