dean.edwards.name/weblog/2007/03/rules/

Rules For JavaScript Library Authors

I wrote this about six months ago before starting work on base2. I decided not to post it at the time as I thought it sounded a little pompous. On reflection, they aren’t bad rules and I managed to stick to them. So, here the rules I wrote for myself back in October.

1. Be unobtrusive
My HTML doesn’t want to know about your JavaScript.
2. Object.prototype is verboten!
This is so important that it needs a rule all to itself. Objects are the basic building blocks of JavaScript functionality. Don’t mess with them.
3. Do Not Over-extend
The less you extend JavaScript’s built-in objects the better. Don’t get me wrong. Native JavaScript objects are a little sparse on useful methods. You will feel obliged to add one or two of your own. But “one or two” is not enough for the creative (library) programmer. Stop! Just add what you need. The less you extend JavaScript’s built-in objects the less you will clash with other libraries.
4. Follow Standards
As a library writer you are defining patterns of JavaScript code. Patterns are signs of weakness in programming languages. Remember, JavaScript and the DOM are continually being specified. If you are going to “fix” something then look to see if it has not already been fixed. Consider available solutions. If you follow standards, then follow them closely (e.g. don’t skip a parameter on a forEach method).
5. Or Follow The Leader
Mozilla leads the way in JavaScript. The creator of the language, Brendan Eich, continues to develop it. New language features are available in Mozilla browsers before any other. If you are going to add language features to JavaScript then look to Mozilla standards first. For example, if you want to extend Array to allow an enumeration method, then call that method forEach instead of each. If you do provide missing language features then follow existing standards closely (see above).
6. Be Flexible
What if I want to modify behaviour without changing the source code of your library? How easy is that? Not easy enough. Make it easier.
7. Manage Memory
People care about memory leaks. Do your job.
8. Eliminate Browser Sniffing
It seems that browser vendors will forever compete by adding new features.;-)As a library author you must keep up with the latest fashions. It is not good enough to browse Ajaxian occasionally. You must slavishly read every blog to find the next hack. Browser sniffing can be addictive.
9. Small is Better
JavaScript libraries have come of age. Some of them now power premier sites. But we are not all on 2MBit DSL lines. So keep your library small. Better yet, provide a build page that allows me to efficiently build my library according to my needs.
10. The Tenth Rule
Good ol’ tenth rule. You can always rely on the tenth rule. The tenth rule is: be predictable. I should be able to guess what your methods do. And if I don’t know what a method is called then I should be able to guess that too.
11. Bonus Rules
  1. Documentation. Annoying but true.
  2. The more namespacing you use, the less likely I am to remember your phone number.
  3. Remember that potentially millions of people will be executing your code.

For the record, base2 does not alter any native JavaScript objects.

Comments (58)

Leave a comment

Dean, one src (about 6 Kb on Gz compatible browsers), JS 1.5 Standard for every browser, without Object prototypes and with every prototype implemented as standard (and few extra features not prototyped too).

This is to tell that You released a library (Base2) that’s not so different from my old JSL concept (and goal) and my new FW … but You was faster than me to release “officially” this cool library.

What do You think about merging our code for a better standard “BaseFX” library development?

I can send You my debugged sources (point 4 and 5 of this post) to implement correctly even XMLHttpRequest for IE 5 or greater (as new perfect String.replace and every other Native methods)

Regards

I agree with most but life is tough in JavaScript land…

1) Being unobtrusive is not easy http://peter.michaux.ca/article/553

3) Don’t extend built in objects at all. Then you don’t have to worry about clashes. I don’t see much difference in writing forEach(myArray, function(a){return a;}) then myArray.forEach(function(a){return a;});

8)It looks like there is some strong sniffing at the top of base2-bom.js

“You must slavishly read every blog to find the next hack”

I don’t think any code in a library should be a “hack”.

9) The Base OOP code seems quite long. JavaScript OOP with “super” in eight lines: http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm

11.1) Writing documentation is a valuable way to look at library code though a different set of glasses. It really helps my development process.

11.2) Namespacing allows people to use a library in a legacy environment. Those who don’t want to type the namespaces can import the namespaced properties into the window object. Without namespaces you are leaving out the legacy developers.

Just some thoughts. The more JavaScript libraries the better since there is more ideas and analysis of browser scripting difficulties. It is unfortunate that we all have such different sets of priorities and can’t just have one library.

The Base OOP code seems quite long.

Yes it is. But I’m happy with it. I don’t really like the other solutions available.

It looks like there is some strong sniffing at the top of base2-bom.js

It is a JavaScript library.:-)My intent is that you should eliminate sniffing for the user of the library.

You must slavishly read every blog to find the next hack

That was a joke.:-)

  • Comment by: -dean
  • Posted:

[…] Passend zum Thema hat Dean Edwards einige Regeln für Autoren von Javascript Bibliotheken aufgeschrieben, welchen ich sehr zustimme. […]

It is a JavaScript library.:-)My intent is that you should eliminate sniffing for the user of the library.

Then, if you’re a fan of jQuery, why don’t you introduce your library to the jQuery developers so as to drop all of their sniffing and depend on base2? That way we could use jQuery and base2 together without problems I guess.

  • Comment by: knocte
  • Posted:

@knocte – if you like jQuery already then I really recommend that you continue to use it. base2 offers nothing more than jQuery already provides. Byte for byte, jQuery provides a lot more power.

This library is not really meant to compete with jQuery or Prototype. Those libraries already provide lots of functionality that base2 does not.

base2.DOM is really aimed at:

  • Comment by: -dean
  • Posted:

[…] Dean Edwards: Rules For JavaScript Library Authors (tags: javascript library rules bestpractices) […]

Thank You Dean to ignore me totally, regards.

Indeed you are right on with all these, but this also leads me to believe that no library is doing all these things. With my recent release of D|C I went through the annoying hassle of writing documentation. I suppose some documentation is better than none, no matter how long your phone number is;)

Predictability is also key since there’s nothing worse than thinking something is something that it isn’t. That is one main reason I allowed the ability to change D|C through registration.

Another thing… man I’m really glad you posted this… because D|C has a simple plugin method which allows you to extend the library without touching the source… one thing I knew I needed to have. And lastly your first rule. Always a given. That was my big argument over the “just add a classname widget philosophy.” Das no good.

About point 4 (Follow Standards)

Both your Function.apply and Number.toFixed don’t respect standards.

function bug(){return [].slice.apply(arguments)};
alert(bug(1,(2).toFixed(2),3));

apply accepts one *optional* argument (as call) and (2).toFixed(2) should return string “2.00” . As I said, bytefw has just solved these common problems … and, for example, the fastest version of unshift should be something like this

[].unshift = function(){
	this.reverse();
	while(arguments.length)	this[this.length] = arguments[--arguments.length];
	return this.reverse().length
};

This post just to tell You that a collaboration should be better without wasted time and with less bugs because, as You said:

look to see if it has not already been fixed

and for example, again, your encodeURIComponent implementation is not standard too while mine one is (and unescape as decodeURIComponent is a bad practice, imho).

bye

@Andrea – what’s wrong with my version of encodeURIComponent()? And, can you keep questions about base2 on the base2 page please?

  • Comment by: -dean
  • Posted:

Dean: how would you propose to implend for instance toJSONString() without prototyping Object?

  • Comment by: Tino Zijdel
  • Posted:

[…] I don’t think I’d really call this a library. It’s more like a band-aid for browsers. But if you are thinking of putting together your own library or band-aid, Dean has provided rules for JavaScript library authors. In a nutshell, make it small, flexible and standards-based. […]

@Dean, about your encodeURIComponent [tested with FireFox]

example

And, can you keep questions about base2 on the base2 page please?

Sure but these are errors about fourth point of this list (these functions don’t respect standard and don’t follow the Leader too)

Regards

@Tino Zijdel – you don’t have to extend the Object.prototype to make json work. Prototype (http://www.prototypejs.org/, rev 1.5.1rc2) has json support built in and they extend the Object singleton (not the prototype). var foo = Object.evalJSON( myJSONString );

@Dean – I dig your article. Great points. I like the idea of a build page to let me choose what components I want to add. As libraries get bigger, and they do overtime, its nice to just pick out what you need. For example, the Prototype SVN repo has all the main parts like (ajax,string,number,event,core) sep. into their own files, but no official build page 8(.

@Andrea Giammarchi – this is a post over Dean’s work, not a place to promote your framework. I like your blog posts too, but try to keep them separate. Your comments on the bugs though, are great. Frameworks should be beaten on by users. Many times I miss little errors in my projects becuase I am too close to them. An outside eye can really help.

  • Comment by: j
  • Posted:

j: what I was actually aiming at is that toJSONString() and parseJSON() are expected to be added in ECMA4. If you like to take the standards approach – as Dean is doing here with Base – that means that in order to have these (near) standard methods available in older (now current) browsers you probably need to prototype Object.

Another example: how would you ‘backport’ for instance the hasOwnProperty() method to IE5?

  • Comment by: Tino Zijdel
  • Posted:

@Tino – well some things are impossible.:-)

  • Comment by: -dean
  • Posted:

“9. Small is Better”

You hit one of the points why I wrote jsPax. A growing part of my js-code uses jQery and various plugins. I had the options of

  1. make a huge bundle with all plugins and load it on every page, regardless if necessary. That way the first visit to the web would be annoyingly slow.
  2. make a smaller bundle for every page. That makes the first page start up faster, but does not use the browser cache at all.
  3. have quite a number of script tags in the head. Only loads the scripts that are necessary and makes perfect use of browser cache.

With jsPax I usually have two script tags on a Page and still make perfect use of the browser cache. BTW I can dynamically change the set of loaded libraries according to the content of the page. That way I don’t have to care if I change the HTML if the according script will be loaded.

[…] Dean Edwards escreveu as regras para autores de bibliotecas JavaScript. São regras que segundo ele, foram criadas para uso próprio, mas imagino que sirva para todos nós. […]

Although base is a different library as jQuery and has a different target audience, I still think that there should be more collaboration between you so as to give a really nice JS framework, avoid code duplication, etc.

  • Comment by: knocte
  • Posted:

I think you should add another two rules:

1 – test your code (Mochikit seems pretty keen on this point)
2 – benchmark your code – speed optimization, stress testing, etc… I think the whole discussion about memory leaks apply here too.

On rules #4 and #5: I must be the only person in the world who thinks forEach loops are bad =(

  • Comment by: Leo Horie
  • Posted:

[…] Dion Almaer wrote an interesting post today onHere’s a quick excerptAs a library author you must keep up with the latest fashions. It is not good enough to browse Ajaxian occasionally. You must slavishly read every blog to find the next hack. Browser sniffing can be addictive. … […]

[…] http://dean.edwards.name/weblog/2007/03/rules/ […]

11 + 7 pravidel pro psaní JavaScriptu Desatero rad pro psaní JavaScriptových kódů od Deana Edwardse (s jedenácti body) a sedmero dalších od Dustina Diaze

  • Trackback by: Dev::Info
  • Posted:

Dean,this is a very nice set of rules, and it is not pompous at all. I would do great work if I was able to stick to just some of them, as I always have some memory leaks and over-extending is my specialty. Thanks for the post, now I can see how many things I was doing wrong.

“base2.DOM is really aimed at:

teachers and students who are learning JavaScript and the DOM programmers, who are already familiar with JavaScript but don’t want to learn a new API web standards zealots”

Dean Your right im one of the students:)And i fully agree with that what You say.

  • Comment by: Jeffrey
  • Posted:

These are some great rules. I totally agree with you on number 6 – Be Flexible, in my opinion it should be the most important rule and much more programmers should stick closely to it, including me. It happened more than few times to me when I had to rewrite most of my code just to change one little behavior thing and that can be really frustrating. So flexibility is a great thing if it can be achieved.

  • Comment by: James
  • Posted:

Are there any documents out there explaining a good way to lazy-load classes and utilities as needed?

I am concerned with the size of my current js library (one file) growing with functions that are not necessarily needed on every single page that the library is included on.

Flexibility is a key to success. I would make “Be Flexible” rule #1 in this list.

Good luck with base2 Dean.

Regards, Marcus

  • Comment by: Marcus
  • Posted:

I would reccomend that people who right JS libraries create different extensions, rather than stuff everything in one file, have the ability to extend it so you only have what you need, it is no good having some fuctions that will be rarely used in a website adding to the size of the file. Have the ability to easy extend the library with files, as and when you need them.

I think this goes with rule 9 you mentioned, this will keep your code small, but still have the functionality to add different functions that you need I think that is a must have.

Do you know of the best way to allow extension inclusion? As in ways to load the extension files into the main core file.

Thanks for the guide Dean!

Nice, the tenth rule seems my favorite:)

Hi Dean, quite a nice collection of rules you have placed here. But don’t you think that in reality one is actually never able of keeping all rules at once? In my opinion everybody has to fix priorities and must find out which of the rules is the most important one for himself. Rule Nr. 9 is very important for me. It’s difficult to understand why there are so many programmers who write that extremely exaggerated code. There still exists a large of number of peoples who is only provided with a bad connection to the Internet and DSL is not yet very widespread.

  • Comment by: Alex
  • Posted:

2. Object.prototype is verboten! =========================

I don´t know much about programming, nevertheless I sometimes stroll over pages like this, to get an impression and ideas.(even without going deep into it, there are sometimes chances, and – what a luck – I have a programmer for such things. But without understand a lot, I was smiling about using the german term “verboten” in relation to a seemingly strict “order” or recommendation about using a coding;-) Please believe me: not everything in Germany is “verboten” ;-) But if something is “verboten” – obey! (ok, that´s a little offtopic, just smile, as I did!) regards from sunny Munich, Germany Hans

Ha ha, I also studied German language in high school and I know that verboten is a really strong word! Dean, cool rules collection, luckily not all of them are “verboten” so they can be bent a little, but if they were only a little bit respected they can be really helpful.

I love tenth rule:)– but thank you for whole list

Greg

web standards zealots

Yar!

Hi Dean, Thx for providing us rules for JavaScript library authors. Indeed you are right on with all these. Make it small, flexible and standards-based:) looks great to me.

  • Comment by: Sebie
  • Posted:

[…] Hier ein paar Richtlinien für Autoren von Javascript-Bibliotheken bzw. Module, gefunden bei Dean Edwards unter http://dean.edwards.name/weblog/2007/03/rules/, ein sehr interessanter Artikel für alle die sich mit Javascript beschäftigen. Diese Tipps sollte man sich zu Herzen nehmen, um Problemen aus dem Weg zu gehen… […]

These rules are really good, if everyone follow these rules the code will be much better to support and to insert little changes…

  • Comment by: Torsten
  • Posted:

[…] Dean Edwards, considerado por muchos uno de los gurus del javascript, ha creado una lista de 10 + 1 reglas para los desarrolladores de librerías javascript, basada en su experiencia a la hora de desarrollar base2. […]

[…] Via aNieto2k me entero de que Dean Edwards (seguramente conocido por muchos que se han metido con el desarrollo en Javascript por sus diversos proyectos y artículos relacionados con este lenguaje) ha publicado una lista de reglas que los desarrolladores de librerias en javascript deberian tomar en cuenta. Estas reglas son en base a su experiencia en el desarrollo de base2 (un framework de javascript). […]

[…] 10 reglas para los desarrolladores de librerías Javascript Dean Edwards, considerado por muchos uno de los gurus del javascript, ha creado una lista de 10 + 1 reglas para los desarrolladores de librerías javascript, basada en su experiencia a la hora de desarrollar base2. […]

[…] Via aNieto2k me entero de que Dean Edwards (seguramente conocido por muchos que se han metido con el desarrollo en Javascript por sus diversos proyectos y artículos relacionados con este lenguaje) ha publicado una lista de reglas que los desarrolladores de librerias en javascript deberian tomar en cuenta. Estas reglas son en base a su experiencia en el desarrollo de base2 (un framework de javascript). […]

[…] for Javascript Library Authors Ver más de: Uncategorized Trackback a este post Esta entrada fue escrita el: Martes 04 de Septiembre de 2007 Anterior: « Adelantándonosa las subidas y caídas de visitas | […]

[…] Dean Edwards: Rules For JavaScript Library Authors (tags: javascript programming library tips rules framework web development reference ajax article api) […]

[…] The current 1.2 development version of MooTools saw a promotion of the Hash Class up from a plugin to a Native type. A Hash is basically a wrapper for native JavaScript Objects. The reason it was created was because as we all know, the Object prototype is off limits! (for a brief explanation… see rule #2). So what can i do with this crazy new thing? […]

[…] One thing that, I believe, makes Base stand out, and Dean as an excellent programmer, is his commitment to standards. Base adherse to some fundamental OOP rules, which Dean has outlined in a nice reference guide for library developers. […]

[…] And I’ve tried to adhere to my own rules for JavaScript library development as much as possible. […]

[…] source: http://dean.edwards.name/weblog/2007/03/rules/ […]

[…] One thing that, I believe, makes Base stand out, and Dean as an excellent programmer, is his commitment to standards. Base adherse to some fundamental OOP rules, which Dean has outlined in a nice reference guide for library developers. […]

JavaScript… Markup Documents to be marked up as HTML Strict, and microformats…

[…] break function in it. But I decided against this for a few reasons. One, it would violate the rules (#3, to be exact). Over-extending a native function would bring more hurt than it would good. […]

[…] 原文在这里:http://dean.edwards.name/weblog/2007/03/rules/ […]

[…] basing all of this off of the outstanding mootools Class system. I really enjoy their code, their approach to modifying JavaScript, and their minimalism. Mootools’ system, in turn, is based on Dean Edwards’ Base.js. As […]

[…] After all these tricks I have to say a word of warning: don’t over-abuse this method since you can end up with complete spaghetti. And don’t mess with prototypes of standard Js objects too much. Bad example: Prototype.js. Good example: YUI. I completely agree with every rule in this Dean Edwards’ post. […]

[…] 原文:http://dean.edwards.name/weblog/2007/03/rules/ […]

[…] 本文翻译自Rules For JavaScript Library Authors,这是Dean Edwards在开发base2时候的一些体会,对于在开发自己的js库的同学应该有较强的借鉴意义。Dean Edwards是公认的javascript高手,jQuery的作者Jhone Resig也很欣赏他。 […]

[…] http://dean.edwards.name/weblog/2007/03/rules/ […]

Comments are closed.