mercredi 26 avril 2017

How to avoid using singleton in a proper way?

I want to refactor my code to apply clean approach.

I have a class user

class User { 
    let name: String?
    let id: String
    var isOnline: Bool

    var mesaageHistory = [Message]()

    init(name: String, id: String, isOnlineStatus: Bool) {
        self.name = name
        self.id  = id
        self.isOnline = isOnlineStatus
    }

}

Then I'm using fabric pattern to create list of my users.

protocol CreateUserProtocol: class {
    func sortArray(inputArr: [User])
}


class CreateUserEntity: CreateUserProtocol {

    static let shared = CreateUserEntity()
    var users = [User]()

    func sortArray(inputArr: [User]){
        var applySortingByDate: Bool = false

        for user in inputArr {
            if !user.mesaageHistory.isEmpty {
                applySortingByDate = true
            }
        }

        if applySortingByDate {
            inputArr.sorted(by: { (first, second) -> Bool in
                (first.mesaageHistory.last?.messageTime)! < (second.mesaageHistory.last?.messageTime)!
            })
        } else {
            inputArr.sorted(by: { (first, second) -> Bool in
                first.name! < second.name!
            })
        }
    }

}

One controller is responsible for appending new users, while another is used to retrieve them and bind them to tableView. Everything is working fine, but I think my solution is not good enough for scaling.

Moreover in one of my VC I use to sort my Users to online and offline. I think, that I shouldn't do that in my VC and to put this logic into my CreateUserEntity

var onlineUsersData = [User]()
var offlineUsersData = [User]()

private func classifyUsers() {
    for user in CreateUserEntity.shared.users {

        print("is user online: \(user.isOnline)")
        print(CreateUserEntity.shared.users.count)

        if user.isOnline == true && !onlineUsersData.contains(user) {
            onlineUsersData.append(user)
        }

        if user.isOnline == false && !offlineUsersData.contains(user) {
            offlineUsersData.append(user)
        }
    }
}

I'd like to rewrite it in proper way, what can you recommend me?

Aucun commentaire:

Enregistrer un commentaire