Careful with JavaScript object literals

JavaScript object literals are very handy, they are just key-value pairs. Very convenient to implement dictionaries and also a very simple implementation of the Singleton pattern:

  1. var message = {sender: 'bob', body: 'hello'};

Duck typing is a technique I use very often as I test-drive my JavaScript code and object literals make it very easy. But overusing them lead to several problems:

I am no longer using object literals in my tests because when I need to add methods to those objects, I need to change too many tests. Also, exposing all those fields lead to feature envy rapidly, producing semantic coupling sooner or later. Although tests are written fast with object literals, I prefer to encapsulate the fields into business objects.

  2. function Message(sender, body){
  3. this.sender = sender;
  4. this.body = body;
  5. }
  6. var message = new Message();