JavaScript - Code reusability

From All n One's bxp software Wixi

Jump to: navigation, search

When building JavaScript code or any programming code, it is always advisable to consider re-usability (reusability).


Wikipedia defines it as In computer science and software engineering, reusability is the likelihood that a segment of source code can be used again http://en.wikipedia.org/wiki/Reusability


In All n One we do everything we can to promote resuability of our code and advise our clients to do likewise.


Here is a simple example. Say we have a function that checks if a question is visible. If it is visible does it have content. Then it informs the user with an error message.


if (document.getElementById('tableid_1').style.display == 'inline-table'){
  if (document.getElementById('strCDA_X_field_0_1').value.length == 0){
    alert('Error in question 1');
  }
}

Say we reuse this code about 25 times in our Form. Then the requirement changes and we need to extend the functionality to also check if there are only numbers in the box. We now have 25 functions to update, not just this one. This useful validation function uses quite a few lines of code. It can be made far more reusable by doing the following.


1 Step 1 - Create a function

Firstly, take the concept and turn it into a function.


function fn_ValidateFieldIfShown(){
  if (document.getElementById('tableid_1').style.display == 'inline-table'){
    if (document.getElementById('strCDA_X_field_0_1').value.length == 0){
      alert('Error in question 1');
    }
  }
}


2 Step 2 - Use parameters

The challenge is that it is still just looking at one field. So we add parameters to the function.


function fn_ValidateFieldIfShown ( strTableId, strField, strMessage ) {
  if (document.getElementById(strTableId).style.display == 'inline-table'){
    if (document.getElementById(strField).value.length == 0){
      alert(strMessage);
    }
  }
}


3 Step 3 - Usage

Now we can resuse this function simply by performing the call to the function. i.e.

fn_ValidateFieldIfShown ( 'tableid_1', 'strCDA_X_field_0_1', 'Error in question 1' );


For twenty five questions, your code goes from a total of 125 lines of code using 4800 characters to 33 lines of code using 2376 characters. This saving makes troubleshooting, code quality and testing a lot easier and it makes maintenance so much handier.


Yes it may add some overhead to your development as you start to use this practice, however it can save hours and hours of your development in the future and make your code far easier for others to manage.