[swift-evolution] [Proposal] Protected Access Level
Brent Royal-Gordon
brent at architechies.com
Sun May 29 18:55:52 CDT 2016
> You seem to be producing a convoluted solution to create a “sharps drawer” but Swift is supposed to be safe. You shouldn’t access the sharps drawer there and there are better ways for us to stop you than to simply “trust” the developer - it’s to do the right thing, and provide a protection level that stops the access where it’s not needed: “protected”.
The thing is, though, the contents of the sharps drawer are *still* sharp even if you're old enough to use a knife. And similarly, APIs like the `state` setter are *still* dangerous even if you've subclassed `UIGestureRecognizer`. To be sure, it is more likely that you'll *need* to set `state`, but it's still not something you should do carelessly or without understanding the consequences.
`protected` fails to acknowledge this. It conflates the act of inheriting interface and implementation with the act of gaining access to dangerous operations. It would be like a drawer which automatically mixed the knives in with the other utensils when an adult opened it.
This is a general problem with traditional OO: Inheritance bundles a whole bunch of separate semantics into a single operation. Obviously some of these are so ingrained in OO that they can't be separated; you're not going to separate inheritance of interface from inheritance of implementation. But the sharps drawer does not *have* to be part of the bundle, and there are compelling reasons to look for a different solution—one which fits this use case better, *and* simultaneously serves other use cases like non-subclassed types.
To give you an idea, here are a couple more potential "sharps drawers" in UIKit which `protected` would not serve well:
* View controller containment. There are very few view controllers which actually contain other view controllers; for most, these calls are a great way to mess things up. And yet some of these members, like `childViewControllers`, are definitely things you need to be able to access from outside a view controller, for instance to find a view controller to present an error message on. `protected` would expose these methods to vast amounts of code that doesn't need them, while hiding them from code that does.
* UIKeyInput and UITextInput methods should only be used by custom keyboards (either `inputView`s or keyboard extensions), but they're exposed to everybody, sitting right alongside methods intended for wide use. The intended clients for these APIs have no inheritance relationship whatsoever with the classes they would need to call them on, so `protected` would be of absolutely no help here.
--
Brent Royal-Gordon
Architechies
More information about the swift-evolution
mailing list