Avoiding temporal coupling

Suppose that we have a code statement that is dependent on another code statement, as shown in the following code:

func sendRequest() { 
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig,
delegate: nil,
delegateQueue: nil)
var url: URL?
var request: URLRequest

/* First request block starts: */
url = URL(string: "https://httpbin.org/get")
request = URLRequest(url: url! as URL)
request.httpMethod = "GET"

let task = session.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) -> Void in

if (error == nil) {
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP (statusCode)")
} else {
print("URL Session Task Failed: %@",
error!.localizedDescription);
}
}
task.resume()
/* First request block ends */

/* Second request block starts */
url = URL(string: "http://requestb.in/1g4pzn21")
// replace with a new requestb.in
request = URLRequest(url: url! as URL)

let secondTask = session.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) -> Void in

if (error == nil) {
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP (statusCode)")
} else {
print("URL Session Task Failed: %@",
error!.localizedDescription);
}
}
secondTask.resume()
}

In the preceding code example, we set two different HTTP requests. Suppose that we do not need our first request anymore and we delete the following code block:

url = URL(string: "https://httpbin.org/get") 
request = URLRequest(url: url! as URL)
request.httpMethod = "GET"

The compiler will not complain but as we deleted request.httpMethod = "GET", our second request is not going to work. This situation is called temporal coupling. If we had immutable definitions with let, we would avoid temporal coupling.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset