Site icon The Winter Blog

Note to self: Use curlies!

This small block of code – it looks clean, and easy to understand

signout: function(callback){
  dropbox.client.signOut(function(error){

    if(error)
      if(callback) callback(false, showError(error));
    
    else
      resetLocalStorage(true, function(){
        if(callback) callback(true);
      });

  });
}

Sadly, it’s also buggy.

When I started programming in javascript, I’d come from a C & Java background, so I encapsulated everything in curlies.

Then sometime later, I started dabbling in Python for work related data processing. I loved how indentation was used to identify code blocks in Python. Didn’t need curlies cluttering everything.

Soon after I discovered that single statements following a loop command (for…) or a conditional (if… else…) didn’t need to be encapsulated inside curlies either. If there was just one statement, you could write it straight after – in same line, or a following one, with any amount of indentation.

Recently, I’ve become addicted to this style of coding. I don’t like unnecessary curlies cluttering the code, and I get rid of them quite aggressively.

Too aggressively as this example shows.

Looking at the code, it appears that the else statement triggers when there isn’t an error. However, in reality, the js parser attaches that else to the if(callback) inside the error conditional.

The correct way to write this is:

signout: function(callback){
  dropbox.client.signOut(function(error){
    
    if(error){
      if(callback) callback(false, showError(error));
    }
    
    else
      resetLocalStorage(true, function(){
        if(callback) callback(true);
      });
    
  });
}
Exit mobile version