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

Wednesday, August 24, 2016

Not funny, but efficient: Nil coalescing operators

For as funny as the "Who's on first?" skit is, it would all be over in a few seconds if they just exchanged lineup cards rather than falling for a series of counter-intuitive homonyms. Again, lineup cards are not funny, but they are efficient.

In the post on optional chaining, I alluded to how developers prefer to write as little code as necessary. Why write more when less will do? In talking about optional chaining, we also talked about what happens when there is no underlying value to our optional and how to handle that - in that case, by returning nil.

But what if we wanted to return something more helpful or accurate than nil? We can do that. And to do that we use nil coalescing operators. Yes, another programming term that on the surface makes little sense or does little to tell us what it actually does. We'll get to that. For now, let's take a look at nil coalescing operators.

In the last example we laid out a scenario where we bring in our defensive substitute, Steven Souza, to play leftfield for Ryan Zimmerman. But in this case, we forgot to make the substition and there's no one out in left! Fortunately, optional binding kicks in and while our value for leftFielder is nil, the program returns our else statement, "No one is playing leftfield!"



In the example below we still don't have a leftfielder, but we do have a faster way of getting to that result (line 14).



What happened? We got the program to return the same string, "No one is playing leftfield!" two different ways. The first way, through optional binding, took about four lines of code (lines 8-12). The second way, with a nil coalescing operator, all took place on line 14. Not too shabby. Here's what the trimmed down version looks like:



Now how do we make sense of that nil coalescing operator moniker? Here's how I explain it to myself: coalesce means to come together to form one group or mass. Here the ?? operator is bringing together the nil value of the empty optional (the stuff to the left of the ??) with the outcome based on what should happen when that optional value is nil (the stuff to the right of the ??) to form a single respone which, in this case, is "No one is playing leftfield!"

We can even take the nil coalescing operator a step further and work in some optional chaining like this:



Pretty slick, right? We can read this as, "If there is a value for leftFielder then capitalize it and return it. If the value for leftFielder is nil, then return, 'No one is playing leftfield!'"

Challenge: Take the example you wrote in the optional chaining post and re-write it using optional chaining then tweet it at me (@randallmardus).

On Deck: Force unwrapping optionals

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.


Monday, August 8, 2016

Caveman Johnny & Clean Cut Johnny

Remember when Johnny Damon signed with the Yankees after his great run with the Red Sox? That was just weird. Or when Albert Pujols left the Cardinals for the Angels? Just didn't seem right.


Sure, parts of those deals made sense. The players wanted bigger, longer-term contracts and got them. But the change of unis and locales just seemed odd to the rest of us used to seeing them in certain cities wearing certain jerseys. It just didn't add up.

Well, the same thing can happen in code. Specifically, when performing operations (addition, subtraction, multiplication or division) with integers and doubles.

But numbers are numbers, right? Why can't we add the integer 3 to the double 3.14? Hell, we can do it in our heads so why can't we do it in code?



We can't add three to 3.14 because we've assigned three to be an integer and 3.14 to be a double. It's like saying Damon can't play for the Yankees because he's still wearing a Red Sox jersey. Damon can only play for the Yankees when he wears a Yankees jersey.

Fortunately, there's a way to address this. We need to do a little type conversion. In this case, we need to convert either cavemanJohnnyHRs to a double or convert cleancutJohnnyHRs to an integer. Here are what both cases look like:



In the first case, we put Johnny in the Yankees Double jersey so we can add his Boston home run totals to his Yankee home run totals.

In the second case, we put Johnny in his Red Sox Integer jersey so we can add his New York home run totals to this Boston home run totals.

Why is type conversion important?
Without type conversions we could not add, subtract, multiply, or divide integers and doubles which would stop cold the programs and functions we've written. With type conversion these programs and functions can run because the numbers are now playing on the same team.

When do we need to use type conversion?
We use type conversion when we know that we'll have to operate (add, subtract, multiply, or divide) integers with doubles in our programs or functions.

Challenge: Find another example of a player going from one club to its rival, write code using type conversion, and tweet it to me (@randallmardus).

On Deck: Want to run a function, but not sure if the data is there or not? Optionals to the rescue.

Thursday, August 4, 2016

Steven Matz, While Loops, & Control Transfer Statements

There's a phone in the dugout for a reason. When the starting pitcher gets in trouble, the manager or pitching coach can pick up the phone and make a call to the bullpen for a reliever or two to start warming up.



Usually, there are a few different reasons for the bullpen to get up. The starter is hurt and needs to come out immediately. The starter is getting shelled and only has a batter or two left in the tank. Or the starter is approaching a pitch count limit.

In our last post we discussed while loops and used Dellin Betances' success against Mike Napoli as an example. In that example, we told Betances to keep pitching Napoli the same way until Napoli's OPS versus him improved to .500.

In this case, though, we have a few possible scenarios to consider.  So let's pretend the Mets' Steven Matz is on the bump and that he just threw his 75th pitch and that he has a 100 pitch limit.



Now let's run through the most dire situation first, that it's true that Matz is injured and needs to come out of the game immediately. Why should we address this first? Because if he has to come out there is no need to go through the rest of the loop up to 100 pitches. He is done now. Here's what that looks like:



So how do we know that the loop won't continue if it is true that Matz is injured? That's what the "break" line does: It exits the loop by breaking out of it.

Now let's go to the second most dire situation, that it's true that Matz is getting shelled. Here's what that looks like:



We use break again here because once we take Matz out of the game there is no need to keep running the loop up to 100 pitches.

And what if Matz is reaching his 100 pitch limit? Let's take a look at what that looks like:



In this case, it is also true that Matz is not getting shelled so as he approaches his 100 pitch limit his coach, Terry Collins, can say, "Good pitchin', kid!" with every pitch, but as soon as he reaches 90 pitches Collins makes the call to get righty Addison Reed and lefty Jerry Blevins up in the 'pen assuming it's a tight game.

This whole rigamarole is called a control transfer statement which just rolls off the tongue, doesn't? That name is about as clear as mud, right? Right. Alas, not all ballplayers are named Ruth and Mays - easy to remember. We have some Yastrzemskis and Rzepczynskis too.

Here's how I like to remember it: control transfer statements help me transfer control of the function depending on the case. In Matz's case, we transferred control to the "it is true Matz is injured" statement when that Boolean was true. We transferred control to the "it is true Matz is getting shelled" part of the function when that was true.

Why are control transfer statements important?
As the Big Nerd Ranch Guide to Swift Programming explains, "Control transfer statements allow you to modify the order of execution in some control flow. These statements transfer control from one chunk of code to another." The Big Nerds go on to say, "In the context of a loop, you can control whether execution iterates to the top of the loop or leaves the loop altogether."

How do we use control transfer statements?
In the Matz example, we used "break" to control the order, or, more specifically, to break out of the loop and end it altogether. If we wanted to control the order in a different way we could use "continue" in the same way we used "break." What would this do? Instead of ending the loop, it would restart the loop at the top and would skip over everything that comes after the "continue" command.

In the Matz example, if we added a "continue" after the final bracket ("}") of the matzGettingShelled portion, it would go back to the beginning and run on an infinite loop. Why? Since the function never reaches its bottom it fails to add pitches to Matz' pitch count and just keeps checking whether he is hurt or if he is getting shelled. Infinitely.

Break and continue: pretty powerful stuff.

Challenge: Create a while loop with control transfer statements for your favorite pitcher, manager, and bullpen and then tweet a screenshot of it to me (@randallmardus).

On deck: Type conversions.