Page copy protected against web site content infringement by Copyscape

Monday, April 13, 2009

Modular Programming

To program in the modular fashion in JavaScript really involves three key things. Using these items in your programming will allow you to create code that can be reused from project to project. These are
  • Creating your own objects
  • Defining general functions to handle common tasks
  • Placing reusable code in external JavaScript source files (commonly *.js or *.mocha files)

NOTE
Like any other language, remember that good comments and documentation are often the most beneficial aspects of programming.


Because creating your own objects is discussed in "Deatils of the Language", take a look at defining functions to handle common tasks. As with other programming languages, there are instances where you have to perform certain processes over and over. many times this might involve a different value of parameters passed, but the processes you go through are the same.

As an example, verify a date entered by a user. This user is suppose to enter the month, date, and year in a form that will be submitted to your Web server for further processing. One of the concerns of the programmer is that he or she needs to have the date in a MM/DD/YYYY format, where the month and date need to be two characters and the year should be four.

To accomplish this task, you can create a single function that pre-pends a "∅" in front of any single digit passed. This function could simply check to see if the value passed was less than the number 10, and, if so, it would perform the pre-pend. By defining this process in a function, a programmer will be able to use the same function for both the month and date verification. This avoids the trouble of writing a function for each. Even though this is a simple example, it illustrates the benefits of function and code reuse.

Programmers can also modulate their programming techniques by including their code in external JavaScript source files. This allows them to write code once, store it in a single location, and include it on many pages by simply referencing the location of the source file. If the function needs to change, they only have to change it in a single fle and not every file that uses it. It is simple things like these that save programmers hours or days of work time.

0 comments: