Tuesday, April 15, 2014

Why The Hell Do I Need Types? Because Fahrenheit can't be less than −459.67

For quite a while I never got the need for a Type System in programming languages. Considering the fact that my first introduction to programming was via PHP and Javascript, and with little or no formal schooling in computer science itself, it is easy to see how I could have easily ignored Types altogether; or worse still consider them an unnecessary overhead.

Why do I need a Type system when all I want to do is to keep in memory the value of say the cost of an Ipad? Can't I just have:

$ipad_cost = 199;

And yeah, if someone reading the code wonders what currency this price is in? well isn't that what comments are for?

// cost is in dollars
$ipad_cost = 199;

Why Types? Why go define a class or Interface for something as basic as this? I may get the idea of Types, but...really?

This was largely my world view regarding Types (an unnecessary overhead and verbosity) until I encountered the situation in which I contemplated on the best way to hold the temperature of a region in Fahrenheit?

long temparetureInFahrenheit = 42L;

or

int temparatureInFahrenheit = 42;

...are temperature values not numerical values? so why not?

But with any of these examples, what is stopping my program from assigning the value −500.67 to the temparatureInFahrenheit variable?

Ha, then my code would be breaking a fundamental law of nature init? as the absolute zero in Fahrenheit is −459.67 which means you can not have temperature with numerical value less than −459.67.

See why then you can't model all numerical values as just an int, long or any of the primitive types that comes with almost all programming languages?

Would it not be nice then, to have a way to make my computer be aware of the fact that the variable temparatureInFahrenheit is actually of a type Fahrenheit and as such has certain rules it has to obey?

Yes, this is what Types are for and useful for.

They are not overheads but a great way to properly model your code and prevent erroneous slips like the one describe above, thereby reducing bugs.

No comments: