[swift-evolution] access control

David Waite david at alkaline-solutions.com
Sun Jan 24 20:54:58 CST 2016


> On Jan 24, 2016, at 1:15 PM, Ilya Belenkiy via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> I think it's possible to believe that your feature would be useful
>> without also believing there's something fundamentally wrong with the
>> current model, and your arguments make it sound to me like you think
>> you're getting a lot more certainty from C++'s "private" than you
>> actually are.
> 
> 
> Data encapsulation is a cornerstone of object oriented programming. Swift has classes, and yet it is impossible to completely hide state / implementation details inside the class. Moreover, it’s impossible to express that something is intended to be completely hidden. Since such a fundamental idea is not supported, there is something fundamentally wrong with the current model. Swift is already a great language, and this issue aside, it’s by far the best language I’ve used. In all other areas Swift does a great job to help the programmer write correct code. This is one weird and very noticeable deviation.

Data encapsulation is indeed one of the cornerstone of OO, but every design decision is a trade-off. Is Python not object-oriented because they lack a private keyword, and have the convention of marking internal items with a leading underscore?

In addition, it is not possible to completely hide state/implementation details in any language (at least that I have experience with). Java, for instance, will let me use the security manager and RTTI to modify private values, and even has JNI code to modify final values as well (this is how System.out works). There are projects that fundamentally depend on being able to access private fields, such as Spring, partly because the Java standard library tells them to (@Injectable).

Even with a “perfect” language mechanism, consumers of the binary will still patch it if they need to in order to get the functionality they want.

The best anyone can do is make the breaking of encapsulation an explicit choice. I’m intuiting that you think that writing code into the file where the class was defined is not explicit enough. I feel comfortable saying to my team members that you have to justify adding code next to a class in the same way you would need to justify changing the implementation of that class. The difference between ‘local’ and ‘private’ access is a copy/paste of a function from an extension into the class body within the same file.

-DW



More information about the swift-evolution mailing list