Be careful with your fix!

I think many times the code grows wrong (also) because of some wrong solutions… Little example: yesterday I was sending an email by Gmail, an attachment was included to the mail.

Correctly, I wasn’t able to send the mail (clicking the “send” button) until the attachment wasn’t completely uploaded.

Thinking about how to accomplish that behavior, some nasty solutions came to my mind: the worst was probably a global variable valorized as false when an operation is performed. The send button routine checks that variable and, if false, it doesn’t execute the sending code.

The implementation would be something like this:

// I add an attachment!
var addAttachment = function(attachmentAsObj) {
  myGlobalNamespace.allowTheSend = false;
  // some code...
};

// I run on the send button click
var sendBtnHandler = function(e) {
  if( myGlobalNamespace.allowTheSend ) {
  // some code...
  }
};

I think it is obvious that this solution is wrong: it moves the problem from the send button to another function (the attachment function, in this case).

Also, should a function implementation start by valorizing the variabile myGlobalNamespace.allowTheSend? A function should be “out of the context”; the add attachment function should add an attachment (somewhere to be defined), all the other stuff is confusing…

The best solution I have found is to fill a stack of operations to be executed before the sending, something like:

// I still run on the send button click
var sendBtnHandler = function(e) {
  if( stack.empty() ) {
  // some code...
  }
};

// I still add an attachment!
var addAttachment = function(attachmentAsObj) {
  // some code...
};

// I run on the add attachment click
var addAttachmentHandler = function(e) {
  // some code...
  stack.push({action: addAttachment, target: attachmentAsObj});
  // some code...
};

The send action could be itself the last operation of the stack (if the button was clicked by the user), so when the stack will execute the last operation (the attachment adding in this case) the send will be automatically executed.

The purpose of this (probably obvious and not needed!) post is to show how a bad solution for a specific problem (here the send button) can involve more parts of the code and make them less clear (the add attachment function): sometimes “it works” doesn’t means “it is the best solution”!

Thanks for reading

Advertisements
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s