Monday, July 18, 2016

Nested Ifs, Else Ifs, & Who's On First

In the old Abbott and Costello skit, "Who's on first?" Lou can't seem to get a straight answer to save his life.



And that's a lot like what happened with our last post where our catcher received three different answers for how to handle Marte on first and Harrison on third.

In addition to that, our code got long, inefficient, and, to be honest, unhelpful. Rather, if we use "nested ifs" or, even better, a series of "else ifs" we can keep our code shorter, more efficient, and helpful.

Let's take a look at the original code again:


And now let's take a look at our more streamlined code using "else ifs":



What differences do we see? We see that the first version is 23 lines of code and that the second is only 15. Much better. We also see that the first version prints out three different outcomes ("Nail him", "There's no play at second because...", and "Call for the shortstop to cut off the...") while the second only prints out, "Nail him." If we are the catcher, we need to make one decision, not three so the second version is much more helpful.

Why did the first print out three different outcomes and the second only print out one? In the first we wrote three separate functions so we got a separate answer for each function. In the second, we wrote one function that gives us one outcome.

Challenge: Re-write your code from the last challenge to turn it into one function using a series of "else if" statements.

On Deck: Operator Shorthand

No comments:

Post a Comment