Wednesday, March 16, 2016

Hide field

All the fields and methods should be private to start with.

In Swift, they are three levels of access levels
- private
- internal
- public

Private and public are obvious. Internal access means public access for the current module, but private for everything else.

The default is the internal access, which means public if we are working with just one module.

But, of course, that is not a good idea. Every class should try to hide as much as it can from the other classes.

One way to achieve this is to make everything private to start with and only change it if need be.

Here is the class used in the previous post:

class Account {
    var isCheckingAccount: Bool = false
    func isChecking() -> Bool {
        return isCheckingAccount
    }
}

We notice that isCheckingAccount is never accessed directly. So we can go ahead and make it private:

class Account {
    private var isCheckingAccount: Bool = false
    func isChecking() -> Bool {
        return isCheckingAccount
    }
}


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.