Javascript Programming Conventions

This document follows the basic outline of the Java Programming Conventions Guide, a copy of which may be found at http://geosoft.no/javastyle.html

Conventions

Any violation to this guide is allowed if it enhances readability.

Guidelines in this document are informed by discussions carried out among the Dojo core developers. The most weight has been given to considerations that impact external developer interaction with Dojo code and APIs. Rules such as whitespace placement are of a much lower order importance fo Dojo developers, but should be followed in the main in order to improve developer coordination.

Quick Reference

Table of core API naming constructs:

Construct Convention Comment
package lower never multiple words
class UpperLower  
public method lowerUpper whether class or instance method. lower_case() is acceptable only if the particular function is mimicing another API.
public var lowerUpper  
constant UpperLower or UPPER_LOWER  

Table of constructs that are not visible in the API, and therefore are optional and carry less weight of enforcement.

Construct Convention Comment
private method _lowerUpper  
private var _lowerUpper  
method args _lowerUpper, lowerUpper  
local vars _lowerUpper, lowerUpper  
Naming Conventions
  1. Names representing packages SHOULD be in all lower case.
  2. Names representing types (classes) MUST be nouns and written in UpperLower case:
    Account, EventHandler
    	
  3. Constants SHOULD be placed within a single object created as a holder for constants, emulating an Enum; the enum SHOULD be named appropriately, and members SHOULD be named using either UpperLower or UPPER_LOWER case:
    var NodeTypes = {
    	Element: 1,
    	DOCUMENT: 2
    }
    	
  4. Abbreviations and acronyms SHOULD NOT be uppercase when used as a name:
    getInnerHtml(), getXml(), XmlDocument
    	
  5. Names representing methods SHOULD be verbs or verb phrases:
    obj.getSomeValue();
    	
  6. Public class variables MUST be written using upperLower case.
  7. Private class variables MAY be written using _upperLower (with preceding underscore):
    var MyClass = function() {
    	var _buffer;
    	this.doSomething = function() {
    	};
    }
    	
  8. Variables that are intended to be private, but cannot be based on the semantics of Javascript, SHOULD prepended with a "_" (underscore) char:
    this._somePrivateVariable = statement;
    	
    NB Note that the above variable also follows the convention for a private variable.
  9. Generic variables SHOULD have the same name as their type:
    setTopic(topic);	// where topic isTypeOf Topic
    	
  10. All names SHOULD be written in English.
  11. Variables with a large scope SHOULD have globally unambiguious names, ambiguity MAY be distinguished by package membership. Variables with small or private scope MAY be more terse still.
  12. The name of the return object is implicit, and SHOULD be avoided in a method name:
    getHandler();	// NOT getEventHandler();
    	
  13. Public names SHOULD be as clear as necessary and SHOULD avoid unclear shortenings and contractions:
    MouseEventHandler	// NOT MseEvtHdlr.
    	
    Note that, again, any context that can be determined by package membership SHOULD be used when determing if a variable name is clear. For example, a class that represents a mouse event handler:
    myobj.events.mouse.Handler	// NOT myobj.events.mouse.MouseEventHandler
    	
  14. Classes/constructors MAY be named basedon their inheritance pattern, with the base class to the right of the name:
    EventHandler
    UIEventHandler
    MouseEventHandler
    	
    NB The base class CAN be dropped from a name if it is obviously implicit in the name:
    MouseEventHandler	// as opposed to MouseUIEventHandler
    	
Specific Naming conventions
  1. Ther terms get/set SHOULD NOT used where a field is accessed, unless the variable being accessed is lexically private.
  2. "is" prefix SHOULD be used for boolean variables and methods.
    NB, Alternatives include "has", "can" and "should".
  3. The term "compute" CAN be used in methods where something is computed.
  4. The term "find" CAN be used in methods where something is looked up.
  5. Ther terms "initialize" or "init" CAN be used where an object or a concept is established.
  6. UI Control variables SHOULD be suffixed by the control type, ie: leftComboBox, topScrollPane.
  7. Plural form MUST be used to name collections.
  8. "num" prefix or "count" postfix SHOULD be used for variables representing a number of objects.
  9. Iterator variables SHOULD be called "i", "j", "k", etc.
  10. Compliment names MUST be used for compliment entities. ie: get/set, add/remove, create/destroy, start/stop, insert/delete, begin/end, etc.
  11. Abbreviations in names SHOULD be avoided.
  12. Negated boolean variable names MUST be avoided:
    isNotError	// are UNACCEPTABLE
    	
  13. Exception classes SHOULD be suffixed with "Exception" or "Error"...FIXME (trt) not sure about this?
  14. Methods returning an object MAY be named after what they return, and methods returning void after what they do.
Files
  1. Class or object-per-file guidelines are not yet determined.
  2. Tabs (set to 4 spaces) SHOULD be used for indentation.
  3. If your editor supports "file tags", please append the appropriate tag at the end of the file enable others to effortlessly obey the correct indentation guidelines for that file
    // vim:ts=4:note:tw=0:
    	
  4. The incompletenes of split line MUST be made obvious:
    var someExpression = Expression1
    	+ Expression2
    	+ Expression3;
    	
    var o = someObject.get (
    		Expression1,
    		Expression2,
    		Expression3
    	);
    	
    Note the indentation for expression continuation is indented relative to the variable name, while indentation for parameters is relative to the method being called.

    Note also the position of the parenthesis in the method call; positioning SHOULD be similar to the use of block notation.
Variables
  1. Variables SHOULD be initialized where they are declared and they SHOULD be declared in the smallest scope possible. A null initialization is acceptable.
  2. Variables MUST never have a dual meaning.
  3. Related variables of the same type CAN be declared in a common statement; unrelated variables SHOULD NOT be declared in the same statement.
  4. Variables SHOULD be kept alive for a short a time as possible.
  5. Loops/iterative declarations
    1. Only loop control statements MUST be included in the "for()" construction.
    2. Loop variables SHOULD be initialized immediately before the loop; loop variables in a "for" statement MAY be initialized in the "for" loop construction.
    3. The use of "do...while" loops are acceptable (unlike in java)
    4. The use of "break" and "continue" is not discouraged (unlike in Java)
  6. Conditionals
    1. Complex conditional expressions SHOULD be avoided; use temporary boolean variables instead.
    2. The nominal case SHOULD be put in the "if" part and the exception in the "else" part of an "if" statement.
    3. Executable statements in conditionals MUST be avoided.
  7. Miscellaneous
    1. The use of magic numbers in the code SHOULD be avoided; they SHOULD be declared using named "constants" instead.
    2. Floating point constants SHOULD ALWAYS be written with decimal point ant at least one decimal.
    3. Floating point constants SHOULD ALWAYS be written with a digit before the decimal point.
Layout
  1. Block statements
    1. Block layout SHOULD BE as illustrated below:
      while(!isDone) {
      	doSomething();
      	isDone = moreToDo();
      }
      				
    2. If statements SHOULD have the following form:
      if(someCondition) {
      	statements;
      } else if(someOtherCondition) {
      	statements;
      } else {
      	statements;
      }
      				
    3. for statements SHOULD be have the following form:
      for(initialization; condition; update) {
      	statements;
      }
      				
    4. while statement SHOULD follow the form in example VI.A.1
    5. a do...while statement SHOULD have the following form:
      do {
      	statements;
      } while(condition);
      				
    6. a switch statement SHOULD have the following form:
      switch(condition) {
      	case ABC:
      		statements;
      		// fall through
      	case DEF:
      		statements;
      		break;
      	default:
      		statements;
      		break;
      }
      				
    7. a try...catch...finally statement SHOULD have the following form:
      try {
      	statements;
      } catch(ex) {
      	statements;
      } finally {
      	statements;
      }
      				
    8. single statement if-else, while or for MUST NOT be written without brackets, but CAN be written on the same line:
      if(condition) {statement;}
      while(condition) {statement;}
      for(initialization; condition; update) {statement;}
      				
  2. Whitespace
    1. Conventional operatiors MAY be surrounded by a space (including ternary operatiors).
    2. Reserved words SHOULD be followed by a space.
    3. Commas SHOULD be followed by a space.
    4. Colons MAY be surrounded by a space.
    5. Semi-colons in for statements SHOULD be followed by a space.
    6. Semi-colons SHOULD NOT be spreceded by a space.
    7. Functions/method calls SHOULD NOT be followed by a space. ie:
      doSomething(someParameter); // NOT doSomething(someParameter)
    8. Logical units within a block SHOULD be seperated by one blank line.
    9. Statements MAY be aligned wherever this enhances readability.
  3. Comments
    1. Tricky code SHOULD not be commented, but rewritten.
    2. All comments SHOULD be written in English.
    3. Comments SHOULD be indented relative to their position in the code, preceding or to the right of the code in question.
    4. The declaration of collection variables SHOULD be followed by a comment stating the common type of the elements in the collection.
    5. Comments SHOULD be included to explain BLOCKS of code, to explain the point of the following block.
    6. Comments SHOULD NOT be included for every single line of code.

posted on 2006-03-25 09:14 毒菇求Buy 阅读(376) 评论(0)  编辑 收藏 引用 所属分类: HTTPOthers

只有注册用户登录后才能发表评论。
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(7)

随笔分类(133)

随笔档案(111)

文章分类(65)

文章档案(53)

相册

收藏夹(30)

BLOG

Book store

Graphics Design

搜索

最新评论

阅读排行榜

评论排行榜