Programming Tips: Centralize Your Code

  1. Find a good text editor
  2. Programming Tips
  3. Avoid the Hammer Syndrome

You should almost never repeat the same basic code more than once. If you need the same routine a second time, seriously consider moving it into a subroutine.

For example, if you wanted to put the date into your “Current Time:” line, we already have the code that creates a date. Unfortunately, if you call it directly you’ll end up with “Today” as the string, because that’s what that subroutine does. Rather than duplicating the portion of the code that creates the actual date, move it out of the “formatDate()” subroutine. Call it something like “makeDate()”. Then, you can call that subroutine both from “formateTime()” and from “formatDate()”.

Another example might be the code we used for prepending a zero to numbers that are smaller than 10. We probably should have created a subroutine that would do that for us, and then call that subroutine every time we need to prepend zeros.

But consider the things you might want to do with a subroutine at the moment you create it. Might we want to prepend something other than zeros? Might we want to pad to three or even four characters instead of just to two? An appropriate subroutine might be called with “thishour = leftpad(thishour, "0", 2);” to ensure that “thishour” has at least two characters, and prepend a zero if it does not. One could then use “indexline = leftpad(pagenumber, ".", 4);” to prepend periods and ensure four characters in the “indexline” string. The function might look something like:

function leftpad(theItem, thePad, minSize) {

newItem = new String(theItem);

while (newItem.length < minSize) {

newItem = thePad + newItem;

}

return newItem;

}

  1. Find a good text editor
  2. Programming Tips
  3. Avoid the Hammer Syndrome