Tonton MyTV dilengkapi intisari rancangan pada smart TV bermula RM4.99 sebulan. Selanjutnya →

Efficient code

Rabu, 17 Julai 2013, 11:57 pm0

From my experience, an efficient code is code that have these characteristics:

  • it works
  • use optimum resource
  • manageable

Note: example codes are in Javascript, specifically Titanium mobile.

An efficient code must be code that can be run. There’s no point of evaluating a code that doesn’t run at all. Secondly, it must solve the problem it’s required to.

Example, a function must return letter ‘S’ for person with weight 50kg and below, ‘M’ for 51-70kg and ‘L’ for 71kg and above. So, the code must comply to this requirement

function getSizeFromWeight(weight) {
  if (weight <=50) {
    return 'S';
  }
  else if (weight <= 70) {
    return 'M';
  }
  return 'L';
}

Note: don’t bother to assign the result to another variable, just return it immediately.

An efficient code that use optimum resources, means the code only create necessary variables and use external resource such as filesystem, network connection, database or plugins only when needed and release those resources when done.

For example, iterating a list of files and getting each of the files’ modification timestamp, for each files that are modified a minute ago will need to be deleted. Some newbie programmer will collect a list of files that need to be deleted and then delete them, one by one. There’s nothing wrong with this method, except the code need to iterate twice in order to delete the expired files, which is inefficient.

var now = new Date().getTime();
var files = []; // assume this contains Ti.Filesystem.File objects
var i = files.length;
while (i--) {
  var f = files[i];
  if (f.modifiedTimestamp + 60000 < now) {
    f.deleteFile();
  }
}

Notes: Some loop statement (e.g while loop) is generally faster that other (for, foreach, do while).

Lazy loading is one of the technique that explains how to use optimum resource. Example, in a Titanium app, when a window opened, we only include those modules that required in order to open the window. If your app need to play audio, only load the audio player module when user invoke the functionality (via play button click etc.)

// open a window
var win = Ti.UI.createWindow();
var TopBar = require('ui/TopBar');
var ContentGrid = require('ui/ContentGrid');
win.add(new TopBar());
win.add(new ContentGrid());
win.open();

// play an audio, when click the play button
playBtn.addEventListener('click', function() {
  var Player = require('lib/Player');
  Player.start(this.audioUrl); // assume playBtn has this property
});

Note: During opening a window, only include UI components required in order to build the app window. And only when the play button is clicked then include the audio player module.

Code manageability means when you need to fix bug, add new feature or rewrite the code to accommodate new infrastructure, the existing code require little or zero adjustment. These small adjustment won’t break the current system.

Example, also in Titanium app, you have a feature to check for a new version of your app from the webserver. In initial release, the app only need to know the version number. Then in subsequent release, you want to add download link, thumbnail image etc. Current code shouldn’t have to be adjusted too much, till it break the calling component.

// initial release
function notifyNewUpdate(p) {
  Ti.UI.createAlertDialog({
    message: 'Version ' + p.version + ' is ready to be downloaded'
  }).show();
}

// subsequent release
function notifyNewUpdate(p) {
  var dialog = Ti.UI.createAlertDialog({
    message: 'Version ' + p.version + ' is ready to be downloaded'
  });
  dialog.addEventListener('click', function() {
    var Updater = require('lib/Updater');
    Updater.download(p.downloadUrl);
  });
  dialog.show();
}

Note: notice that input parameter to notifyNewUpdate() function is maintained. This allow developer to add more or remove unused parameter without breaking the function call.

Tulis komen: