什么是减少冗余代码的最佳方法

时间:2018-04-05 16:13:04

标签: ios swift nsurlsession

我希望减少从ExDeveloper获得的代码中的重复。我有一个服务器型号,我所有的网络代码。现在我在这里展示了3种方法。但最终它会成长和发展会有70多种方法。我不想重复所有方法中常见的任务代码。

如果不使用Alamofire等第三方,最好的方法是什么?

func login(userName: String, password: String, onSuccess: @escaping(JSON) -> Void, onFailure: @escaping(Error) -> Void){
    let url : String = ""
    let request: NSMutableURLRequest = NSMutableURLRequest(url: NSURL(string: url)! as URL)
    request.httpMethod = "GET"
    let session = URLSession.shared
    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        if(error != nil){
            onFailure(error!)
        } else{
            print(response as Any)
        }
    })
    task.resume()

}

//====================

func signUp(userName: String, password: String, email: String, onSuccess: @escaping(JSON) -> Void, onFailure: @escaping(Error) -> Void){
    let url : String = ""
    let request: NSMutableURLRequest = NSMutableURLRequest(url: NSURL(string: url)! as URL)
    request.httpMethod = "GET"
    let session = URLSession.shared
    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        if(error != nil){
            onFailure(error!)
        } else{
            print(response as Any)
        }
    })
    task.resume()

}

//====================


func forgot(email: String, onSuccess: @escaping(JSON) -> Void, onFailure: @escaping(Error) -> Void){
    let url : String = ""
    let request: NSMutableURLRequest = NSMutableURLRequest(url: NSURL(string: url)! as URL)
    request.httpMethod = "GET"
    let session = URLSession.shared
    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        if(error != nil){
            onFailure(error!)
        } else{
            print(response as Any)
        }
    })
    task.resume()

}

2 个答案:

答案 0 :(得分:0)

您可以将请求拆分为更多模块化组件,例如网络层。

查看本指南:https://medium.com/@danielemargutti/network-layers-in-swift-7fc5628ff789

答案 1 :(得分:0)

在您编写上述代码时,每个功能都完全相同。所以把它放在一个他们都称之为单独的函数中。如果有些部分不相同(您没有提供),则将它们传递给共享函数。如果有更改的代码,请将其作为函数参数传递。

简而言之:提取不会改变的部分,并传递作为参数的部分。