19.12. Test Driven JavaScript Development

A couple of weeks ago, I was attending a three-day workshop for agile developer skills. The workshop was split into five topics: Colaboration, Refactoring, Design & Architecture, Continious Integration and Test Driven Development. Especially the session about Test Driven Development was very interesting. Although I know the principles of TDD I was really impressed by the demonstration of solving a simple exercise (a coding kata) done in Java by the instructors of the workshop. It was not so much the coding in Java that was interesting for me, it was the combination of writing a test, executing the test with a shortcut from the IDE, see the test fail, write the implementation and re-start the test again within the IDE. You will say “that´s test driven development- it´s nothing new!” and you are right! But is there a way to do Test Driven Development in the same way for JavaScript? I mean writing a test, execute the tests with a shortcut from the IDE, see the test fail, implement the method and re-start the test? Yes, there is a way! So let me show you what I have done to do the same coding kata (called Fizzbuzz) with JavaScript.

Weiterlesen

03.12. Setting up an own QA Environment for Javascript

Nearly every PHP project comes up with a great set of tools to assure the quality of source code; unit tests are a no longer a „nice to have“ feature, they are common components in new projects. While unit tests help you to provide solid interfaces and proof the functionality of a certain method, there is a long list of tools that check the quality of the source code itself with many different metrics. Each of these mentioned tools reports its results into a XML file, which can easily be interpreted by a continuous integration server like Jenkins. The benefit is enormous: After every commit to your version control system your continuous integration server triggers the execution of the tests and the source code quality analysis and shows the result in meaningful diagrams. As a developer you get a direct feedback and you can make a prediction on the status of the entire project, because if even the smallest units work fine, there is a good chance that the whole system runs stable.
Weiterlesen

JavaScript Pitfalls for PHP-Developers

A couple of years ago, PHP developers only had to have strong knowledge in the language itself and experience in some PHP frameworks and libraries, additionally skills in MySQL were expected.
If we take a look at our current job advertisement, these knowledge is still important, but also skills in JavaScript are asked and strongly desired. If you wonder why JavaScript is so popular at these times, my answer is quite simple: The browser is no longer a stupid instrument to view some static websites on the internet- the browser turned into an (Web-) Application Platform that provides more content then plain text. This results in more and more complex sites and therefore in much more source code. One of the reasons for this progress is AJAX, which is the art of exchanging data with a server, and updating only parts of a website (with JavaScript). Therefore JavaScript is the big winner on this evaluation, because it is available on nearly every browser, needs no plug in or any additional software and it is easy to learn. In the early days of the internet we used JavaScript to create some lousy effects or did some simple checks for any input fields. These days are gone, it is not unusual to have more JavaScript code than PHP code in large projects. Coding with JavaScript is not the same as coding with PHP, that´s the reason why I will write down some typical pitfalls for a PHP developer whose coding JavaScript.

Data types

There are two major data types in JavaScript, the primitive one (Boolean, String, Number, …) and Object (Array, Function). To check the data type the keyword typeof keyword might help you. But be aware! Objects are the fundamental units of JavaScript and virtually everything in JavaScript is an object and takes advantage of that fact. Even the primitive data types have so called “primitive object wrapper” and there´s great potential for wrong usage of the typeof keyword and checking the data type. Here is a small overview what you will get if you use the typeof keyword with several variables:

Variable

typeof Variable

{company: ‚Mayflower‘}

object“

[‚Mayflower‘,’PHP‘]

object“

function(){}

function”

a simple String”

string”

123456789

number”

true

boolean”

new String(“Mayflower”)

object”

new Employe( )

object”

You can see, you will not always get what you expect. Therefore it´s not always a good choice to check the data type with typeof. A better approach is to use the constructor property to identify the data type of a variable.


var myArr = [ ];
if (myArr.constructor === Array) {console.log(“yes, I am an Array!”)}

The downside of this approach is the needed comparison to a known data type. If you create your Array with the new operator, you can get the data type with the prototype property, like this:


var myArr = new Array();
console.log(myArr.prototype); // Array()

Array !== Array

In the PHP world an array is a wildly used data type and we are differ between the zero indexed, comma separated array and hash tables of key-value pairs, better known as associative arrays. In JavaScript an Array is just a simple zero indexed list of values- nothing more. There is no associative array in JavaScript. There is no trailing comma support for IE (causes an error)


var myArr = ['Mayflower','PHP','JavaScript'];

In JavaScript is something like an associative array, but this has nothing to do with the Array data type. The JavaScript world calls this an object literal and is a collection of key value pairs.


var obLiteral = {company: “Mayflower”, offices: ['München','Würzburg'] };

By the way, you are right if you say “the syntax looks like for a JSON string”. The syntax for an object literal and a JSON string are pretty similar with one main difference: For a JSON string the property names need to be wrapped in quotes to be valid. For object literals the quotes are only required if the property name have spaces or any other not valid identifiers.

for (… in … ) !== foreach

When you are working with Arrays the you surely know the foreach construct to iterate over the array. Against the common opinion, the for (… in … ) construct is not the JavaScript equivalent of foreach and it is not the best way to iterate over an array in JavaScript.

DO: Use the for (…) loop for iterations over array objects
Every JavaScript array provides a length property, so it is the best practice for iterating over a JavaScript using a simple for construct.

DON´T: Use the for (… in …) loop for iterations over array objects
It is not impossible to use the for (…. in … ) loop with an array (you remember, arrays are objects, too), but it can lead to some ugly errors because JavaScript is a powerful language and you can add functionality and properties to nearly every existing object (this is called augmentation). If you iterate over an augmented array object you will not get only the elements of the array, you will even get the augmented functionality and this may occur in an error.

The thing with the semicolon

Have you ever heard about “line termination with semicolon insertion”? JavaScript provides a mechanism that adds a semicolon to the end of a line if you forget it. At a first look this may be helpful but it can be the reason for endless debugging sessions. Imagine the following situation:


function user(){

return


{

company: “Mayflower”,

business: “PHP Development”

}

}

The user function will run without any error and will return a valid value (Ok, it´s undefined but it´s a valid return value). It´s not the desired object literal because the semicolon insertion terminates the function after the return.

I´m sure there are a lots of more pitfalls for PHP Developers, if you are interested in real crazy JavaScript I recommend a visit at http://wtfjs.com/.

Javascript best practises: debugging und logging Vortrag@Mayflower-München

Am kommenden Donnerstag, den 25.03.2010 findet wieder ein öffentlicher Vortrag im Mayflower Büro in München statt (Mannhardtstraße 6, S-Bahn Isartor).
Beginn ist um 18:00 Uhr, Thema des Vortrags ist „Javascript best practises: debugging und logging„.

Lange Jahre wurde Javascript von vielen Entwicklern nicht so ernst genommen. Durch den vermehrten Einsatz von AJAX und der einfachen Handhabung von Javascript-Frameworks und Libraries ist die Akzeptanz gestiegen und Javascript ist aus der Webentwicklung nicht mehr wegzudenken. Unter dem Titel „Best Practises- Debugging und Logging JS“ zeigt uns Martin Ruprecht Mittel und Wege, wie man effektiv die Fehlersuche mit Javascript betreibt.

Die „Donnerstags-Vorträge“ werden sowohl in München als auch in Würzburg gehalten. Bei Interesse einfach das Blog beobachten, um auf dem Laufenden zu bleiben!
Wir freuen uns auf viele Teilnehmer!

Euer Weg zu uns