My general approach when designing APIs is to explicitly name required 
parameters and then have the last parameter be an options object. For instance, 
let’s say you’re designing an API to move an element to particular location. 
I’d design the API as:

function moveTo(element, x, y, options){

}

In this case, you know you’ll always need the element and the x and y 
coordinates in order to do the move, so I list those explicitly. You may later 
add options such as animate to that new position from the current position, or 
add a bounding box.

If you’d like a real-world example, take a look at the YUI Cookie utility 
(which I created). The methods are designed in this manner:
http://developer.yahoo.com/yui/3/api/Cookie.html

-Nicholas
_____________________________________________________
Nicholas C. Zakas
Twitter: @slicknet
Blog: http://www.nczonline.net/



From: Peter van der Zee 
Sent: Thursday, January 13, 2011 8:43 AM
To: [email protected] 
Subject: Re: [JSMentors] JS API Design - Accepting Parameters

On Thu, Jan 13, 2011 at 5:37 PM, Arlo <[email protected]> wrote:

  Example Method:
  A.) function drawPolygon( points, polyOptions ) { ... }
  B.) function drawPolygon( options ) { ... }

  I feel that with option B I can expand functionality a lot easier than
  with option A.  Does anyone have advice or common pitfalls when taking
  approach B?  I appreciate any input.



Always put internal ("private") arguments at the end, even when 
extending/improving. That way you dont have to worry about breaking scripts 
because, well, they're internal.

Other than that, I'd say use your own judgement for which arguments to pick. 
Something like drawPolygon will always need coordinates but it might not always 
need a color or line thickness. Those are the kinds of values you would request 
in an options object.

- peter
-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/
 
To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/
 
To unsubscribe from this group, send email to
[email protected]

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to