Читать книгу Reliable JavaScript - Lawrence Spencer - Страница 11
INTRODUCTION
THE EASE OF UNINTENTIONALLY BREAKING JAVASCRIPT CODE
ОглавлениеJavaScript has a perverse sense of humor. In a staid, compiled language, if you have a line of perfectly correct, debugged code running flawlessly in production like this one
and then accidentally bump the x
key on your keyboard so that you now have
the compiler will emit a stern message that you should be more careful next time. JavaScript will happily run the code and give the value of undefined
to myVariable
. “Let's have fun and see what happens!” she says.
When you want to change the name of a property, JavaScript likes to play hide-and-seek. You might think that searching your entire source tree for
would turn up all the places to change. “No, no, no!” JavaScript says with a grin. “You forgot to search for ['myProperty']
.”
Actually, you should search with a regular expression that allows spaces between the brackets and the quotes. Have you ever done that? Neither have we.
And then, depending on her mood, she may or may not let it come to your mind that you should also search for constructs like this:
When it is so hard to accomplish even such a trivial refactoring, you can imagine how easily mistakes can find their way into your code. Code that is not amenable to refactoring almost defines the word “brittle.”
How can you avoid these problems? If there is one concept that we hope to preach and practice in this book, it is test-driven development. In the absence of a compiler, tests are your best defense against error.
JavaScript is also more than amenable to playing by the rules of software engineering. In fact, because of her extremely..um..creative nature, JavaScript may need them more than most languages.
We have met many developers who are open to this message and would like to learn more about how to proceed. We hope you are one of them.