Skip to content

Comment on Access Control in Swift

Comments

Note that as seems to be in vogue these days (Go, Rust), access to a class's methods and fields is never directly tied to code being "inside" the class; even `private` entities are accessible from anywhere in the same source file. I guess this is a good thing, as it avoids awkwardness with anything implemented as a function rather than a method, and works as a substitute for most cases where "friend" would be acceptable coding style in C++.

You can say it's "in vogue" these days, but C had private, public, and internal visibility (private = declared in .c file, public = declared in public .h file, internal = declared in private .h file). It's not just that you can technically accomplish this in C, but people actually use this all the time. Look at almost any library and you'll find this. Other languages have had module and library scopes for accessibility for decades as well. It's really an aberration that some languages make it so that data structures are the scope for symbol accessibility. C++'s accessibility rules are just bizarre and awkward for polyglots.

I wrote about how it is like C [0] the other day. I should update the post with links to the Apple blog and some of things said on the forum. Maybe tonight.

[0] http://blog.human-friendly.com/swift-access-controls-are-lik...

Yes, C++ gave tools and then "language lawyers" started to introduce practically dubious rules where every class has to carefully guard its own variables.

In the saner practice, however, you want to develop subsystems where the classes that are the part of the subsystem cooperate to the common goal, not protect themselves from their peers (some "OO" C++ language lawyers are certainly already offended by my claim). Even if some class is in charge for something, it's easier when more classes can at least see some pieces of the data without making a lot of getters and setters "just because."

In Go at least, you can certainly enforce private fields and methods on a strict to be accessible only within the scope of the package.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.