[swift-evolution] Make class and struct members private by default / Type-Based access

Ted F.A. van Gaalen tedvgiosdev at gmail.com
Mon Apr 3 16:15:57 CDT 2017


Hello, 

(this is related to:     Type-based ‘private’ access within a file)

Currently class and struct items  (variables, functions..) are public by default
that is,  always accessible outside the class’s scope
for example:  (Swift 3.1) 

class AsItIsNow
{
    private var a = 10
    private var b = 12
    
    func aPlusB() -> Int
    {
       return a + b
    }

    private func helperFunction()
    {
       . . . 
    }
}

Having all items public by default has the following disadvantages:

   • All members are exposed by default, wether intended or not. This
      could lead to class misusage unintended by the class’s creator. 

   • To prevent undesired access of functions vars etc. inside a class
      one has to prefix often too many items with the ‘private’ access modifier keyword.
      Most of the functionality  and items inside a class or struct are meant to 
      be used internally  and should  not be revealed to the outside world. 

   • It does not comply (contradicts)  with lexical scope as in Swift functions etc. 
  
   • It is frontally different to most other programming languages and
     therefore confusing for those coming from C#, C++, Java, Pascal etc. 

I experience this as fundamentally wrong. 

Imho it should be as in the next example, everything in a class
is private by default. To access/deploy items from outside they 
need to be defined with the ‘public’ access modifier, 
not the other way around, please. 

class AsItShouldBeImho
{
   var a = 10  // private by default
    var b = 12   // also
    
    public func aPlusB() -> Int
    {
       return a + b
    }
    
    func privateFunction()   
    {
       . . . 
    }
}

‘public’  could be an inferred attribute
for items defined with getters and setters.. 
or the compiler would demand public
for getters and setters..

The ‘protected’ keyword is needed. 
‘protected’ would mean that the items are
accessible in subclasses   (class only)  

private items would also be inaccessible in
class extensions. 

It is as yet unclear to me why it has not been done
like so from the beginning of Swift…

I’ve been lost in the eternal discussions over private access modifiers,
the volume of it makes me think that (either way in this discussions) the whole
scope definition is wrong in Swift .
especially using a file as scope limiter. 
Imho there should be lexical scope only.
as in most other programming languages.
If done so correctly , one wouldn’t even need the ‘private’ keyword...

Kind Regards
TedvG

www.tedvg.com <http://www.tedvg.com/>
www.ravelnotes.com







 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170403/fb949f31/attachment.html>


More information about the swift-evolution mailing list