ios - 将方法分组为更通用的方法是一种好的做法吗?

标签 ios swift function oop

我需要在 viewDidLoad 中完成一些设置工作。我已将所有辅助方法添加到配置方法中,因此在 viewDidLoad 中,我只需调用configure() 即可一切正常。这是好的做法还是将代码耦合在一起视为不好的做法。任何提示表示赞赏!

//configure() called in viewDidLoad
private func configure() {

    UserProvider.sharedInstance.fetchUser(with: AuthProvider.sharedInstance.currentUserId(), completionHandler: {
        user in
        guard let user = user else { return }
        self.currentUser = user

        self.setupViews(currentUser: user)

        self.setupLocation()
    })
}


private func setupViews(currentUser: User) {
    setupCollectionView()
    updateDatasource(currentUser: currentUser)
}


private func setupCollectionView() {
    collectionView.dataSource = datasource
    collectionView.delegate = datasource
}


private func updateDatasource(currentUser: User) {
    UserProvider.sharedInstance.fetchNearbyUsers(for: currentUser, completionHandler: { nearbyUsers in
        guard nearbyUsers.isEmpty == false else { return }
        self.datasource.update(with: nearbyUsers, collectionView: self.collectionView)
    })
}

最佳答案

是的,将代码模块化为函数是一个很好的做法。

但是命名应该更具可读性和稳定性。

如何?

假设您想要在同一个 View Controller 中配置一些UI 相关更改。例如导航栏颜色、导航标题等

并且您想要更改一些约束值。您也想像现在正在做的那样配置网络。因此,如果您将所有代码都放入配置函数中,则会造成一些误解。在这种情况下,您可以分解得更像

func configureUI(){//write ui configuration here}
 func updateConstraintsValue() {//write constraints change code here}
 func configureAuth() { //write Authentication configuration code here}

关于ios - 将方法分组为更通用的方法是一种好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44362007/

相关文章:

ios - 在创建 Mapbox MGLShape 之前验证 geojson

function - 从 Liquid 中的字符串中获取子字符串?

ios - UITableView 中的颜色替代 UITableViewCell?

ios - CoreData 将一条记录标记为最爱(互斥)

ios - 如何从钥匙串(keychain)中删除 nsdictionary 以进行替换

ios - 如何从父 UIViewController 调用容器中嵌入的 UIViewController 中的方法?

objective-c - SWIFT Closure 语法 - 从 Objective C 转换

javascript - 如何使用 setInterval() 重复调用带有参数的函数?

r - 如何根据R中的条件获取相关变量

android - 发送数据到 Android 设备 Notification to IOS 设备