What is method chaining ?

In this article I will explain what is method chaining, where we can use and what are the advantages of using. Method chaining is a very less discussed and used topic. Almofire iOS framework mostly uses the method chaining concept.

The concept of method chaining is each method initialize some class properties or do something and returns self so that you can call another method on this. Making functions chainable is quite easy and can allow us to write using an almost DSL-like syntax.

Let’s consider the below method.

func makeRequest(requestURL: String?, method: String?, parameters: [String: String]?, completionHandler: @escaping ([String:AnyObject], bool) -> Void)

In the above func if some parameter is not required we have to pass nil for that.

Now Let’s consider the below APIRequest class.

class APIRequest {
    var url:URL?
    var method = HTTPMethods.get
    var params:[String:String]?
    enum HTTPMethods: String { // http methods
        case get = "GET"
        case post = "POST"
        case put = "PUT"
        case patch = "PATCH"
        case delete = "DELETE"
    }
    
    func urlString(_ urlString: String?) -> APIRequest {
        
        if let urlString = urlString {
        self.url = URL(string: urlString)
        }
        return self
    }
    
    func method(_ method:HTTPMethods) -> APIRequest {
        self.method = method
        return self
    }
    
    func parameters(_ params:[String:String]) -> APIRequest {
        self.params = params
        return self
    }
    
    func response(response:@escaping([String:AnyObject], success: bool) -> Void) {
        // create URLRequest with the http method, url, parameters etc and do the api call using URLSession method.. say use DataTask.
        let resultDictionary = ["result":["Result values1","Result values2","Result values3","Result values4"]]
        // let resultDictionary be the output of the API call made. Now, call the completion closure and pass the value.
        // If the call is success pass true else false.
        //DispatchQueue.main.async {
            response(resultDictionary as [String:AnyObject], true)
       // }
        
    }
}

If we use the above class to make an API call, it will look something like this.

APIRequest().urlString(“www.google.com").method(.post).parameters(params).response { (resultDict, success) in
      print(resultDict[“result”]!)
}

//----------------
// prints the following in console.
(
"Result values1",
"Result values2",
"Result values3",
"Result values4"
)

So you can see the difference between the first method I mentioned above and this one. In the first method you have to pass everything in one method only and you get the response back. But in the below APIRequest method chaining way, you call one method after another.

Advantage of Method chaining:

Here the greatest advantage is that we need to call any chaining method only when required. If we are doing a ‘get’ method call, we can skip the ‘method’ method call as ‘get’ is given as the default method inside the code. Also if some parameters are not required, we may skip those calls too, but in case of the first method you just can’t skip it, you have to pass nil or some value as method argument. So using method chaining you right less code which is makes more sense.

Note:
Don’t confuse with swift optional chaining.
If you like this article please comment and share.
About the author:
Vivek Das,
iOS Application Developer 8 years of exp.
Working as Senior Associate at Tata Digital Health

Comments

Post a Comment

Popular posts from this blog

AutoFill OTP in iOS12 new feature (iOS12).

Let’s understand what is optional in Swift and how to use !!