I have an api class, which make api calls and most of the calls are the same but some returns something (JSON data) and others don't. Also there is a call to check only if a param is registered and return true or false. So at this moment we have three api calls, with exactly the same code but little differences or returns values.
these are two examples, the first one will set an internal class property with JSON data, the second will return true or 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
}
The code is almost identical. My question is what is the best practise to do this? As far as I know, duplicate code is not the best thing to do. But right now I don't see clearly another way.