TypeError: Cannot call method 'someMethod' of undefined
Your browser or the Node.js interpreter will tell you in which file and on which line that error has occurred. Then, you’ll start a very mundane task of examining the code of a 3rd party library, if it’s has not been minimised, of course. Eventually, you will find out that you have forgotten to provide one of the arguments required by a function.
You may even see a more obscure error. Let’s take the standard Node.js library for an example, more specifically, its
http module. It has the
request() function that sends an HTTP request that can be meticulously configured with an object you pass into. What if you accidentally confuse one of the object’s attributes, for example, instead of typing
hostname you write
Then, you will see an error saying exactly the following:
throw er; // Unhandled 'error' event Error: connect ECONNREFUSED
Urgh, what could it mean? Has Google suddenly gone down? No, you should have read the documentation more carefully and remember that the attribute is called
Okay, so, where does the problem lie? Is it a developer’s problem that they have accidentally made mistake and spent hours debugging? Let’s face, we all make mistakes. Some tools though provide better feedback than the other ones.
Can Static Typing Really Help?
We presume that
Well, partially… Statically typed languages are still prone to similar issues. Let’s take Java as an example. It can provide great feedback to a developer during a compilation. What about the run time though? How many time have you seen a
NullPointerException creeping out of nowhere?
NullPointerException anyhow different from the problem with
Consider the following example:
The code is written in a statically type language, so you cannot pass an
int or a
String. What about passing a
That problem will not be caught when compiling the code, instead there will be a runtime exception. The code snippet above is fairly simple. Imagine calling
customer.getName() somewhere deep inside the method? That would be ‘fun’ to debug…
It’s hardly a surprise that even Java, a statically typed language, has libraries, such as Guava, one of which goals is to solve the problem by failing fast.
Developers, using Guava, would strive to use
Preconditions to fail as early as possibly and provide meaningful information if something goes wrong, e.g.:
Here, we arrive on a very important point when it comes to the API design. Do fail fast. Please, do. I also beg you to provide an informative message to a user. We all use 3rd party libraries because they solve problems we don’t want to specialise in. And we don’t want to dive into the code of those libraries to find out why we see that message about some undefined value or something even more esoteric.
All we want to see is a nice message saying that a certain argument is not what a function expects. That can be implemented with a fairly simple piece of code: