Tuesday, August 23, 2016

Steven Souza, No-No Saving Catches, & Optional Chaining

In the last post, we talked about how optional binding is like a late inning defensive replacement: It's Steven Souza, Jr. taking over left-field for Ryan Zimmerman to secure Jordan Zimmermann's no-no for the Nationals in 2014.



But what if you wanted to bring in a defensive replacement and then have the PA announcer introduce that defensive replacement? In other words, what if you wanted to perform an action after checking to see if the value is there or not?

Why would you want to do this? Because it is more efficient than performing optional binding and then writing a function with a couple possible outcomes depending on whether or not there was a value behind the optional. And, as they say, developers are lazy so why write more code than is needed?

Here's what that looks like:



So what is happening here? First, we did some optional binding in line 8. Then, after that block of code (ie, the stuff between the two { } brackets) that's where we did our optional chaining and we did it by creating a new variable.

What exactly is going on in line 14? Let's read it out loud: If there is a value for leftFielder, then put it in uppercase and set it to the variable nowPlayingLF. Fortunately, there is and we get "SOUZA" returned on the right hand side. We are chaining the result of whether or not there is a value for our optional (the variable leftFielder) to what we then want to do with that value (uppercase it).

And what happens if there is no one out in leftfield, that is, there is no name, no data, no value for our leftfielder optional? Here's what happens:



What is happening here? First, we commented out line 6 so that the optional, leftFielder, has no value. Then we did some optional binding in line 8. From line 8 the program can tell that there is no value for leftFielder so it runs the else statement (line 11) and declares, "No one is playing leftfield!"

Outside that code block (after the { } brackets), we run our optional chaining like we did before, but this time it returns nil. Why? Let's read it out loud: "If there is a value for leftFielder, then put it in uppercase, but if there is no value for leftFielder assign nil to the variable nowPlayingLF." And that's how we got there.

Challenge: Re-write the code above with your favorite defensive replacement and the position s/he came in for and then tweet it to me at @randallmardus.

Up Next: Optionals & Nil Coalescing Operators


No comments:

Post a Comment