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.

No comments:

Post a Comment