3 ms·
Primitive types such as string/number/... are really not a great example when it comes to showcasing the benefits of static typing. I don't know why it's so com
by realharo 10y ago
Primitive types such as string/number/... are really not a great example when it comes to showcasing the benefits of static typing. I don't know why it's so common.
A better example would be something like
// let's pretend the values are not dummy values, etc.
function getWeather(encodedWeatherString) {
return { temperature: 50, windDirection: 'east' }
}
function getWeatherFromUrl(url) {
return { temperature: 20, windDirection: 'east' }
}
All is well. Some time later, someone decides to add some extra data to getWeatherFromUrl, but not to getWeather, and then tries to use this extra data in some place, i.e.:
function getWeatherFromUrl(url) {
return { temperature: 20, windDirection: 'east', time: new Date() }
}
function displayWeather(weather) {
return "It was " + weather.temperature + " on " + dayOfWeek(weather.time.getDay())
}
Which will cause an error when called on the weather object returned from getWeather(), because the time property will be undefined.
This is of course a tiny tiny example where it is trivial to keep track of all the data structures in your head. But even in projects that are not that huge, it can get pretty inconvenient and mentally draining very fast. It's a lot more enjoyable to not have to deal with that kind of stuff, and just have one Weather structure defined for the whole project that everything has to adhere to and that everything can rely on.