SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

Rule Request: ACL ordering within type contents

Open LucasVanDongen opened this issue 3 years ago • 0 comments

New Issue Checklist

New rule request

The rule is meant to have the most visible (public) fields or functions on the top of your class, struct or enum. So for example public var goes above internal var which in turn goes above private var. However public init would come below all of the var declarations, including the private vars. This could be an extension of type_contents_order where the contents are further sorted on access control, for example by adding an optional parameter to it.

This rule should be added to enforce consistency in an arbitrary way with as added bonus that the stuff you're most likely to interact with as consumer of the object / struct / enum is also the first you find when scrolling through the file. I have no strong opinion on this rule being mandatory or not, I think everybody's code would improve with better sorting of contents but type_contents_order is optional as well so it would be strange (and even impossible without type_contents_order?) to enforce this rule by default.

If you think this is a good idea, I can try to implement the rule myself.

One thing that can make it slightly difficult to implement is the fact that often fields don't have an explicit acces control modifier.

Would not trigger

class Car {
    public var horn = "Honk"
    internal var: owner: String
    private var tireType = "Whitewall"

    init(owner: String) {
        self.owner = owner
    }
    
    func replaceOwner(with newOwner: String) {
        owner = newOwner
        honk()
    }

    private func honk() {
        print(horn)
    }
}

Will trigger

class Car {
    internal var: owner: String // Public fields should precede internal fields
    private var tireType = "Whitewall" // Public fields should precede private fields
    public var horn = "Honk" // Public fields should precede private fields

    private init(owner: String, tireType: String) { // Public initializers should precede private initializers
        self.owner = owner
        self. tireType = tireType
    }

    init(owner: String) { // Public initializers should precede private initializers
        self.owner = owner
    }

    static func owned(by owner: String, having tireType: String) -> Car {
        return Car(owner: owner, tireType: String)
    }

    private func honk() { // Public functions should precede private functions
        print(horn)
    }
    
    func replaceOwner(with newOwner: String) { // Public functions should precede private functions
        owner = newOwner
        honk()
    }
}

LucasVanDongen avatar Jul 09 '21 09:07 LucasVanDongen