Showing posts with label optionals. Show all posts
Showing posts with label optionals. Show all posts

Friday, August 26, 2016

Successfully Rationalizing One's Way Out of a Suicide Squeeze & Force Unwrapping Optionals

My Babe Ruth League baseball coach was not afraid to call risky plays. He even made me pitch once which even I knew was a terrible idea, but, somehow, we escaped the inning unscathed.

There was one time, though, when I got the call for a suicide squeeze. He hoped it would go like this:



I figured it would end up like this:



Understand, I was not the Ruthian figure that I am now (...). I had a streaky bat which typically didn't get hot till the last three games of the season and this was not one of the last three games of the season. What I lacked in braun, I made up for in brains.

But you say, who needs braun to lay down a suicide squeeze? And you're right. But my team sucked, I sucked, and runs were few and far between. If I missed the bunt, if I fouled it off, or if I bunted it in the wrong direction, we're toast and the opportunity is lost.

So I did some quick math: First, this was junior high baseball: There was no shortage of errors, wild pitches, and passed balls to be had. While the pitcher threw hard, today he had proven to be wild. And while catchers in this league were typically one of the three best players on their team (behind the pitcher and the shortstop), the kid behind the plate today was not a brick wall or vacuum cleaner. Plus, as a right-handed batter, granted a 5'4" 100 lbs one, the catcher still had to catch the ball, get around the hitter, and make the tag to successfully stop a suicide squeeze.

While I got the sign to lay down the suicide squeeze from my coach at third, I told myself, "Self, if you get a good pitch, bunt it. If you get a bad pitch, let it go: The runner from third will still score."

What happened?

I got a bad pitch.

What happened to the runner?

The runner scored.

Barely.

Then what happened?

My coach chewed me out for not laying down the bunt like I was told to. Fair enough.

So far we've talked about how we can use optionals to protect our code from crashing when the data or values we hope are there are not there. But sometimes you are so confident about something you just want to go through with it consequences be damned.

I told myself not to bunt because I had faith that the pitcher, the catcher, or both would blow it, I didn't bunt, and we scored. It worked.

Going forward with such faith in Swift programming is called force unwrapping an optional. Again, doesn't quite roll off the tongue, but stick with me. Let's take a look and then walk through it.



What's going on here? Let's pretend a PA announcer has to announce the next hitter, but it's a crucial point in the game. One team might switch pitchers. The other team might bring up a different hitter. There's uncertainty everywhere. So the PA announcer makes the name he's going to announce next an optional (See the ? after String on line 6?) just in case he doesn't get the name in time.

Turns out, Sanchez is going to hit. We know that because we've assigned "Sanchez" to the string variable playerSurname. Now that we know who's going to hit, the announcer can make his announcement, "Now batting, Optional("Sanchez")\n". If we read between the lines, we can assume that the player's first name is not Optional and that that is just some computer language in there.

In fact, that is how I explain why we call them wrapped or unwrapped optionals. In the above example, the string optional "Sanchez" is still wrapped in the "Optional("string")\n business. And wrapping, as we like to think, adds an extra layer around something.

 But what if, in this moment of uncertainty about who's up next, the PA announcer goes out on a limb and just announces Sanchez as the next hitter. Well, that's what forced unwrapping an optional is like. Here's what that looks like:



By adding an exclamation point (!) to playerSurname on line 8 we force unwrap that optional and we know we've force unwrapped it successfully because one, we see, "Now batting, Sanchez\n" on the right hand side of line 9, and two, because that Optional("Sanchez")\n business is now gone. Why is the optional wrapping gone? Because we've forced unwrapped it.

Now, what happens if the PA announcer doesn't know the name of the next hitter, but mumbles out something just the same? Here's how that goes:



In short, it doesn't go well. The announcer thought he could get away with mumbling, but instead he gets a Bronx cheer, a big error message appears in red on the Jumbotron in centerfield, and the fans crash his booth (or, at least, his program).

Why is force unwrapping optionals important?
Sometimes you just want a program to run because you are that confident that data will be there. If that's the case, force unwrapping optionals is important and useful.

When does one use force unwrapping?
One only force unwraps optionals when absolutely certain that the data is there. This is like swinging at a 3-0 pitch. In most cases, you don't do it. But when you're down by three with two outs in the bottom of the ninth at home, the pitcher is gassed, and you've got your best hitter up, give 'em the green light because that's about as ideal as it's going to get.

Challenge: Re-write the example above with the name of your favorite relief pitcher and then tweet it to me (@randallmardus).

On Deck: Classses

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


Friday, August 12, 2016

Optional binding, the late inning defensive replacement of Swift programming

In the last post, we introduced the idea of optionals and how optionals help developers to keep their programs running in case there is no data where there should be data.

Optional binding is like a late inning defensive replacement. You hope you don't need him because he's by no means your best hitter, but you're glad he's there in case your first baseman, middle infielder, third baseman, or catcher catches a case of the yips, just fouled a ball of his leg and can't walk, or just dove into the stands and left half his face in the third row.



Normally, you don't need the defensive replacement, but sometimes you want to make sure nothing funny happens. Normally, the data you need is there and you don't need optional binding, but sometimes there's a chance that it won't be there and that you'll need it.

For example, if you forget to log how you did in your baseball game today, optionals would help deal with that lack of information and keep your baseball performance app tracker from crashing. Here's an example where all the data you need to calculate slugging percentage is there:



As you can see, there is a ? after the abs Double data type. The ? is there because I thought there was a chance a user could forget to include their number of at bats (the same could be said for the other stats) and I wanted to make sure that that variable, abs, was an optional.

In this case, abs has a value and that value is 100. Because there is a value the function runs. But what happens if there is no value? That's where our utility infielder comes to the rescue. Let's take a look:



What would happen if we wrote the same function, but forgot to make the abs variable an optional? This is what that would look like:



What happened? We got an error and our program crashed. And this is why optional binding is helpful. It provides a safety net instead of the program just falling apart and crashing.

And now that we've gone through these three different possible outcomes, let's take a closer look at that, "if let tempAbs = abs" line. What the hell is that? In baseball terms, that is exactly when the manager calls on the defensive replacement (tempAbs) and tells him to go for the starter (abs) because he's afraid the starter is going to drop the data ball. In coding terms, that is when we bind the optional (abs) to a temporary constant to avoid that dropping of the ball to make us call the game altogether (ie, crash the program).

In comes the bench player, tempAbs, out goes the starter, abs. As the manager, you now feel better about your defense and as a programmer, with optional binding you can feel better about your program not crashing.

Challenge: Calculate OPS and make one of the data inputs (hits, at bats, walks, etc) an optional then tweet me your code (@randallmardus). 

On Deck: Optional chaining

Bonus for Faubert: After Jeter left that game, Alex Rodriguez filled in for him at short. Who filled in for Rodriguez at third?

Tuesday, August 9, 2016

Ichiro, Sweaty Bats, and Optionals

First off, congrats to Ichiro Suzuki on his 3,000th MLB hit on Sunday! A triple at that! Four years ago David Waldstein (@DavidWaldstein) of the New York Times wrote this great piece about Ichiro and his bats. In the article, Waldstein talks about how Ichiro chooses his bat based on the humidity and the bat's weight that given day.


Can you imagine if all hitters logged the weight of the bat they used everyday for an entire season? After seven game days in a row we might see that the constant bat weight may have something to do with the player's fatigue and advise a lighter bat as the week goes on or depending on the stuff of the opposing pitcher. 

So let's say we created an app that allows hitters to track their slugging percentage on different amounts of rest and different weights of bats. At first we want to establish a baseline so let's have the user use the same bat weight for a month of games.



After a month we get this data using the same 30 ounce bat:

Slugging percentage after a day of rest =  0.433
Slugging percentage after no rest for two days = 0.442
Slugging percentage after no rest for three days = 0.453
Slugging percentage after no rest for four days =  0.441
Slugging percentage after no rest for five days = 0.427
Slugging percentage after no rest for six days = 0.412
Slugging percentage after no rest for seven days = 0.392

So the first day back after a day of rest the hitter hits well, but really peaks on the third day. After that, the hitter starts to show signs of fatigue (this, of course, does not account for the different pitchers the hitter faces and is all completely hypothetical). 

That gives us a baseline of data. With that data in mind, let's have the hitter adjust his/her approach to what weight bats to choose on which days of the schedule. 

var batWeight = 31, slugging percentage after a day of rest = 0.438
var batWeight = 31, slugging percentage after no rest for two days = 0.446
var batWeight = 30, slugging percentage after no rest for three days = 0.459
var batWeight = 29.5, slugging percentage after no rest for four days = 0.451
var batWeight = 29, slugging percentage after no rest for five days = 0.442
var batWeight = 28.5, slugging percentage after no rest for six days = 0.435
var batWeight = 28, slugging percentage after no rest for seven days = 0.427

Much better! 

But what if the hitter forgot to track a day, forgot to put in what weight bat s/he used and how s/he hit that day and we still tried to run the program? What do you think would happen? We'd have an error and the program wouldn't run messing up our entire experiment. 

Other than goofing the hitter so s/he doesn't do that again, how can make sure that the program continues to run? Fortunately for us, Swift offers us a chance to do this through optionals. 

When do we use optionals?
Anytime you ask a user to input information, be it the number of hits they got that day or the weight of the bat they used that day, there is a chance they won't put the info in. This is when we want to make sure we declare our optionals. 

How do we declare optionals?
In the beginning of our program, we lay out our variables and constants. This is a good time to declare our optionals. In our case, they look like this:


See the ? after our declared data type, Double? That ? declares that that Double, absFirstDayAfterRest for example, is an optional. We make "at bats the first day after a day of rest" because there is a chance the user will forget to enter how many at bats they had that day. 

How do optionals work?
Instead of returning an error when a program comes across an empty value (e.g., no at bats or hits logged), a Swift optional returns nil as you can see in the example above. What is nil? Good question. Nil is a rather abstract concept and can become confusing rather quickly. 

Think of nil like Eddie Gaedel pinch hitting for Josh Donaldson who had too many tacos last night and is now paying the price: We expected Donaldson to bat (akin to entering a value), but instead he's "occupied" and we get Gaedel (nil). Sure, Gaedel's going to bat, but chances are he's not going to get a hit, but at least the game will continue. What would happen if you didn't send anyone up to bat? The ump would assess an out, the manager would blow his stack, would argue with the ump, chew out his own players, and the game would go nowhere. At least with nil the game continues. 


Why are optionals important?
Nil helps us keep playing the game as opposed to nothing which is like sending no one up to bat and getting us an automatic out (e.g., an error that stops the program altogether). We can work with nil, we can't do anything with nothing.

That's a good place to stop for now. Optionals aren't easy and there's more abstraction to come.

On Deck: Optional binding.