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?
No comments:
Post a Comment