jeudi 18 octobre 2018

Patterns: Singletons vs. Static vars and methods approach

(I am still pretty new to programming and Swift)

So I am reading a lot about the Singleton Pattern. I am currently using it to store groups of global state in my first app. I am reaching a point where I wonder which approach to implement API client classes and similar with.

"Singletons are bad...", "...at least use them very carefully", "they can make testing very hard" is what - I guess we all heard about, or experienced the the resulting challenges first hand.

I am personally not far enough in my project, so that I would have experienced problems with tests myself yet.

That being said, the question is: Are Structs with static vars and static functions having the same issues?

To illustrate what I mean, I've tried to write the same heavily simplified and exact same(?) scenario twice.

1. A singleton being worked with by from a view controller:

struct APIClientSingletonClass {

    static let shared = APIClientSingletonClass()

    var stateOfSomehting: Bool = true
    var stateOfSomehtingMore: Bool = false
    var stateNumber: CGFloat = 1234
    var stateOfSomehtingComputed: CGFloat {
        return stateNumber * 10
    }

    func convertSomethingToSomethingElse() {
        // calling method in self like this:
        otherMethod()
    }
    func otherMethod() {
        // doing stuff here
    }
}



// Calling APIClient from outside:
class ViewControllerTalkingToSingleton: UIViewController {

    var api = APIClientSingletonClass.shared

    override func viewDidLoad() {
        super.viewDidLoad()
        api.convertSomethingToSomethingElse()
        api.stateOfSomehting = false
    }
}

2. Another approach:

struct APIClientStruct {

    static var stateOfSomehting: Bool = true
    static var stateOfSomehtingMore: Bool = false
    static var stateNumber: CGFloat = 1234
    static var stateOfSomehtingComputed: CGFloat {
        return stateNumber * 10
    }

    static func convertSomethingToSomethingElse() {
        // calling method in self like this:
        APIClientStruct.otherMethod()
    }

    static func otherMethod() {
        // doing stuff here
    }
}


// Calling APIClient from outside:
class ViewControllerTalkingToStruct: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        APIClientStruct.convertSomethingToSomethingElse()
        APIClientStruct.stateOfSomehting = false
    }
}

What do you guys think? Is approach 2 falling into the same traps that seem to make Singletons such a double-edged sword?

Any input is really appreciated! Best from Berlin

Aucun commentaire:

Enregistrer un commentaire