Which approach would lead to an API that is easier to use?

Posted by Clem on Programmers See other posts from Programmers or by Clem
Published on 2014-05-28T14:45:34Z Indexed on 2014/05/28 15:53 UTC
Read the original article Hit count: 340

Filed under:
|

I'm writing a JavaScript API and for a particular case, I'm wondering which approach is the sexiest. Let's take an example: writing a VideoPlayer, I add a getCurrentTime method which gives the elapsed time since the start.

  1. The first approach simply declares getCurrentTime as follows:

    getCurrentTime():number
    

    where number is the native number type. This approach includes a CURRENT_TIME_CHANGED event so that API users can add callbacks to be aware of time changes. Listening to this event would look like the following:

    myVideoPlayer.addEventListener(CURRENT_TIME_CHANGED, function(evt){
        console.log ("current time = "+evt.getDispatcher().getCurrentTime());
    });
    
  2. The second approach declares getCurrentTime differently:

    getCurrentTime():CustomNumber
    

    where CustomNumber is a custom number object, not the native one. This custom object dispatches a VALUE_CHANGED event when its value changes, so there is no need for the CURRENT_TIME_CHANGED event! Just listen to the returned object for value changes! Listening to this event would look like the following:

    myVideoPlayer.getCurrentTime().addEventListener(VALUE_CHANGED, function(evt){
        console.log ("current time = "+evt.getDispatcher().valueOf());
    });
    

    Note that CustomNumber has a valueOf method which returns a native number that lets the returned CustomNumber object being used as a number, so:

    var result = myVideoPlayer.getCurrentTime()+5;
    

    will work!

So in the first approach, we listen to an object for a change in its property's value. In the second one we directly listen to the property for a change on its value. There are multiple pros and cons for each approach, I just want to know which one the developers would prefer to use!

© Programmers or respective owner

Related posts about JavaScript

Related posts about api