【问题标题】:is it best practise to write the same method twice when I need it multiple times with different return type?当我需要多次使用不同的返回类型时,两次编写相同的方法是最佳实践吗?
【发布时间】:2016-09-07 21:26:31
【问题描述】:

我有一个 api 类,它进行 api 调用,大多数调用是相同的,但有些返回一些东西(JSON 数据),而另一些则没有。还有一个调用来检查参数是否已注册并返回真或假。所以此时我们有三个 api 调用,它们的代码完全相同,但几乎没有差异或返回值。

这是两个示例,第一个将使用 JSON 数据设置内部类属性,第二个将返回 true 或 false:

///Call an api with the given url param
private func call(){
    let request = NSMutableURLRequest(URL: NSURL(string: userApiCallUrl)!)
    request.HTTPMethod = "POST"

    request.HTTPBody = postParam.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {
            // check for fundamental networking error
            print("error=\(error)")
            return
        }
        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

        self.setJsonData(responseString!)
    }
    task.resume()
}
///Call to check if UDID exist. Returns true or false. For the moment returns true allways
private func callToCheck()->Bool{
    let request = NSMutableURLRequest(URL: NSURL(string: userApiCallUrl)!)
    request.HTTPMethod = "POST"

    request.HTTPBody = postParam.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {
            // check for fundamental networking error
            print("error=\(error)")
            return             }
        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
    }
    task.resume()
    return true
}

代码几乎相同。我的问题是这样做的最佳做法是什么? 据我所知,重复代码并不是最好的办法。但现在我没有清楚地看到另一种方式。

【问题讨论】:

  • 使返回类型通用。喜欢AnyObject or Any
  • 如果方法相同,但返回类型不同,则返回“Object”并检查该对象实例中所需类的实例

标签: ios json swift2


【解决方案1】:

如果你真的想要两个函数,把第一个改成

private func call(){
    callToCheck ()
}

我想一个“return”应该是“return false”。

【讨论】:

    【解决方案2】:

    在调用函数时使用额外的参数,比如说 int 类型。然后切换 int(案例 1 将返回一些数据,案例 2 将返回其他类型的数据)。作为一般建议。在您的最终函数返回中使用 NSMutableDictionary,将初始 int 分配为键的值,每个案例的结果作为具有结果值的其他键。毕竟你会知道在你的 回调您处理的女巫案件以及您使用的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-16
      • 1970-01-01
      • 2020-12-20
      • 2016-09-25
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      相关资源
      最近更新 更多