2012年08月28日--编码规范

  The java code convention document:

Back-end Rule

Structure

com.platform.gui
  |-- common
  |   |-- factory
  |   |-- web
  |   |   |-- action
  |   |   |   `-- BaseAction.java
  |   |   |-- filter
  |   |   |   `-- IdentifyFilter.java
  |   |   `-- interceptor
  |   |       |-- Interceptor1.java
  |   |       `-- Interceptor2.java
  `-- cloud
      |-- common
      |   `-- web
      |       |-- action
      |       |   `-- CloudBaseAction.java
      |       |-- filter
      |       |   `-- CloudIdentifyFilter.java
      |       `-- interceptor
      |           |-- Interceptor1.java
      |           `-- Interceptor2.java
      |-- login
      |   |-- action
      |   |   `-- LoginAction.java
      |   |-- spring.xml
      |   |-- struts.xml
      |   `-- package.properties
      `-- user
          |-- action
          |   |-- UserListAction.java
          |   |-- UserAddAction.java
          |   |-- UserEditAction.java
          |   `-- UserDeleteAction.java
          |-- model
          |   `-- User.java
          |-- service
          |   |-- real
          |   |   `-- UserServiceRealImpl.java
          |   |-- mock
          |   |   |-- UserServiceMockImpl.java
          |   |   `-- mockdata.xml
          |   `-- UserService.java
          |-- util
          |   `-- UserIDGenerator.java
          |-- UserConstants.java
          |-- spring.xml
          |-- struts.xml
          `-- package.properties

 

Shared Library

  • Do not commit any internal shared lib to cvs. For example, perf_common.jar, Log4VO-1.0.jar, etc. We should copy it from shared directory when build package.
  • Do not commit some special third part lib to cvs. For example, YUI and Birt library. We should put the YUI and Birt library to shared directory and copy it when build package.
  • Before we commit new third part library into cvs, please confirm which function of this library and which code will use it. If we don't know, please ask someone to get the detail.

 

Basic Java Rule

  • Put the classes that have the similar functionality in one package. Do not put too many classes under one package. For example:
    • In the com.platform.common.gui package, there are JNI class, base bean class like SessionUserInfo, manager class like GuiConfigurationManager, common wrapper class like Wraper*.java.
    • In com.platform.vem.gui.api package, all the VEM part api under this package without sub package. Here includes JNI, API interface, API real and mock implementation, and mock data file. That is too chaos. If I am a new developer, I cannot find the class what I need. In addition, if we want remove one module, what can I do? I need filter too many classes in build file.
  • Make our java class simple and only do one kind of things. For example, for UserServiceImpl class, we should only put the list, add, edit, delete, search methods in it, another example is the SessionUserInfo class, it should include the basic properties and some getter/setter methods, but should not include any business logic method like setUserSession(), setUserCookie() and renewToken(). We can put these logic into a Manager, Util or Filter class.
  • Basically, we at least split our java classes to three layers: model, service and action.
    • Model: This is domain object like User, Host, Cluster etc. For this type class, we should put it into a model package.
    • Service: The middle level between model and action layer. This level focus on provide interface to manage model layer and support for action layer.
    • Action: This function of this layer is prepared the data for view, and organize the data and invoke service layer to operate model(domain) object.
  • For spring, struts configuration files and resource properties file, we should split by module. Do not put all configuration or resource messages in one big file.
  • For debug level log, please use the below usage:
if (logger.isDebugEnabled) {
    logger.debug(var1 + var2 + var3);
}

 

Model Layer Rule

  • Make our model class as simple as possible. It should only include some properties and some getter/setter methods. That is ALL.
  • Make our model class Implements the java.io.Serializable interface. It can make our class can be persisted.

 

Service Layer Rule

  • By default, each service layer should include at least three classes.
  1. UserService: This is interface defines some exposed method.
  2. UserServiceRealImpl: This is real implementation class that invoke back-end api or operate database.
  3. UserServiceMockImpl: This is mock implementation class that use mock data.
  • Do not reference the HttpServletRequest, HttpServletResponse and HttpSession class in service layer class. This will make service layer class too difficult to test.

 

Action Layer Rule

  • In the Action class, we shouldn't use session.setAttribute() or request.setAttribute() methods to put the parameter in the HttpServletRequest or HttpSession instance. These two methods will make our Action and Jsp page too difficult to maintain. For request level operation, in struts1, we can use ActionForm to solve it, in struts2, we should use action property to solve it. For session level operation, we can use Cache it solve it.
  • Each action only should do one thing, do not make bold(big) action class to do everything. And the logic in the action should be simple. In an action class, we should only do the following things:
  1. Get the data from Service layer, and set it to one or more action properties.
  2. Organize data from front-end form for service and invoke service method to do action.
  3. For some special case, the model(domain) is not enough for front-end, we can transform the domain object to View Bean object, vice versa.
  4. Do not put user authentication and authorization code in action class. That should be in Filter class.
  5. For the global action and row action, we should provide another action class(es) to do it.

For example:

public final class UserListAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	
	private List<User> users;
	
	UserService userService;

	public String execute() throws Exception {
		users = userService.list();
		return SUCCESS;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}
}
  • For struts1, each action has own form, do not share the same action form for different action. If we shared the same action form, we will found the action form is too big.
  • Use struts validator to validate form. This is very useful for us and this will make development very easy.



    读后笔记:
    1、从整体包结构可以清晰看出包结构里面的类分工明确,公共基础类划分为一个包,以便其他包继承或者实现;每个Web包下面都包含有action(动作)、filter(过滤器)、interceptor(拦截器)三个小包;每一个用例下都有action、model、service三个小包,以下会介绍这几个包的具体规则。
    
    2、项目中不可避免地会引用到其它库,但在小组开发中不建议直接提交内部共享库、专用的第三方库,而应该在创建包的时候就把这些相应的库复制到指定目录中。当然在提交新的第三方库时,应该确保引入这个库哪些功能或者代码我们将会引用到,如果不清楚就应该问其他人获得更多的细节。

    3、Java基本规则:
        3.1 应该尽可能地把具有相似功能的类放到同一个包里面,而不应该把许多类放到同一个包。这点对于日后的开发维护以及小组加入新元素时是非常有帮助的。
        3.2 应该尽可能地使我们定义的类尽量只做同一类事情使其尽量地简单。
        3.3 通常我们会把类分成三层:模型层、服务层、响应层:
             模型层:其实这个层也可以称作实体层,一般存放着实体类。在设计规则上,应该让该层的实体类尽量的简单只包含属性和setter()、getter()方法。当然这些实体类都要事先序列化接口,使得该类能够持久化。
            服务层:这个层处于模型层和响应层中间,主要提供接口管理模型层以及对响应层的支撑。在设计规则上,服务层一般至少包含如下三个类/接口(例如):UserService(该接口只要定义了暴露在外面的方法)、UserServiceRealImpl(该类是真实数据的实现)、UserServiceMockImpl(该类是模拟数据的实现)。应该尽量避免使用如HttpServletRequest, HttpServletResponse 和 HttpSession类在该层,不然将会导致很难进行测试。
            响应层:这一层感觉有点类似于MVC里面的View层,但又有别于View层。主要把数据显示到界面、组织数据调用服务层来操作数据层。在设计规则上,不应该把session.setAttribute() or request.setAttribute()方法放在HttpServletRequest or HttpSession里实例化,这两个方法使得Action和JSP页面很难维护。对于请求级别的操作,在Struts1中,我们可以使用ActionForm进行解决,在Struts2中,我们可以使用Action属性来解决。对于会话级别的操作,我们可以使用缓存来解决。在该层每个Action应该尽量只做一件事儿不应该把所有事情都放在一个大的Action类里面。
        3.4 对于像spring、struts等配置文件和资源属性文件,我们应该把它们按模块划分,而不要把它们混乱地放在一个大文件里。
        3.5 如果我们有采用log进行debug时,可以使用如下格式:
            if (logger.isDebugEnabled) {
                logger.debug(var1 + var2 + var3);
            }


Front-end Rule

 

 Structure

{webapp}                  The web application name, for example egogui.
  `-- host                The host module directory.
      |-- list.jsp        The list page for host. 
      |-- add.jsp         The list add for host.
      |-- edit.jsp        The list edit for host.
      |-- view.jsp        The list view for host.
      |-- js              The javascript directory for host.
      | `-- host.js       The javascript file for host.
      |-- css             The css directory for host.
      | `-- style.css     The css file for host.
      `-- images          The image directory for host.

 

 JSP and Tag

  • Split the Tag code and JavaScript code in our Jsp pages. This is very important. For example, the following JavaScript code is very difficult to read.
<c:forEach items="${storageMap}" var="storageList">
      <c:set var="count" value="0"/>
      tempStorages=new Array();
      <c:forEach items="${storageList.value}" var="storage">
          tempStore = new Array();
          tempStore["SRID"]="<c:out value="${storage.id}"/>";
          tempStore["SRName"]="<c:out value="${storage.name}"/>";
          //var tempStorages=new Array(tempStore);
          if (template_storage["<c:out value='${storageList.key}'/>"] == null) {
             template_storage["<c:out value='${storageList.key}'/>"] = new Array();
          }
          tempStorages = template_storage["<c:out value='${storageList.key}'/>"];
          tempStorages[<c:out value='${count}'/>]=tempStore;
          template_storage["<c:out value='${storageList.key}'/>"]=tempStorages;
          <c:set var="count" value="${count + 1}"/>       
      </c:forEach>
   </c:forEach>

Actually, we can use JSON to make it simple.

  • Do not use expression language in JSP page. We should use Tag to do the same thing. In practice, we found the page is un-readable if we introduce the el in JSP page. We suggest to use JSTL or struts tag to do the similar things.
  • For tag, we need think careful about the function of the tag before we implement it. One we release a tag, it must be stable. These two tags are bad: headerHTMLJS.tag and headerHTMLCSS.tag. For these two tags we can use sitemesh or ties to implements. Actually, we can write the js and css direct or in a configuration file.

    读后笔记:
        1、对于JSP页面中含有Tag和JavaScript,我们应该尽量地使两者分离别混合在一起,不然将会导致很难阅读代码。
        2、对于以上的问题,我们可以使用JSON来解决。如果可以使用Tag的话就尽量避免使用表达式语言。在实际过程中,我们会发现像JSTL和Struts标签式经常被采用的。
        3、当我们在实现或者采用tag时,应该能够保证它的稳定性。像headerHTMLJS.tag and headerHTMLCSS.tag都是不建议采用的。




Files Organization

We need create "css" file to be used for putting external css document under your own project. If your project need some images you should check the common's images folder firstly, if these images exist already so use them directly, otherwise you should create a new folder "images" under your project, put these images in it.

 

Naming Conventions

 

Semantic Approach

In general, a semantic approach defines classes names considering the "meaning" a certain element has on your page two simple guidelines for developing a better CSS code:

1. Use lowercase characters to define your class and use uppercase letters to separate multiple-words classes (ex. "mainContent).

2. Optimize CSS code creating only the main classes and reusing HTML standard tags for child elements (h1, h2, p, ul, li, blockquote,...).
For example, don't use this approach:

	<div class="main">
  <div class="mainTitle">...</div>
  <div class="mainParagraph">...</div>
 </div>

...but use this:

	<div class="main">
  <h1>...</h1>
  <p>...</p>
 </div>

 

Names

The names of the classes need to be clear and descriptive. Names should not contain style-information.

 

Case

First for the case of the names themselves. Start the class names with lowercase letters and start each embedded word in the name with a capital. HTML elements are in lower case in anticipation of XHTML.

 

Unit

We take pixel(px) to define the spacing between elements and take point(pt) as a standard unit to control font size.

 

Spacing, Punctuation and Brackets

Generally spacing promotes readability, so let's take advantage of it.

 

Empty lines between style definitions

Allow the separate style definitions to breathe, by adding one (and only one) empty line between them.

 

1 tab = 4 spaces

Indentation also helps with the readability of the code. So put every property-value pair on a new line and indent it with 4 spaces from the beginning of the line. You can use a tab for indentation.

 

Space after colons

Visually emphasis on the separation between a property and value, by adding a space after the colon, like:

	.class {
   prop: value;
}

and not

	.class {
   prop:value;
}

or

	.class {
   prop:      value;
}

 

Curly brackets

Curly brackets embrace all property-value pairs in a style definition. The opening bracket must be on the same line as the selector identifier and the closing bracket on a new line.

Example

	.header { 
   font-size: 2em;  
}
	.navigationBar,
.content,
.header i { 
   font-size: 0.8em; 
   border: solid black 1px;
   border-left: solid black 5px;
   border-right: solid black 5px;
}

 

Global CSS Definition

Gloable css definition be used in common css document only, once you use global css definition under your porject will break the relationship between other css document, so NOT allowed global css definition under your project.

	body {
    background: #FFF;
    font-family: arial,helvetica,clean,sans-serif;
    font-size: 10pt;
    margin: 8px;
}
ul, li {
    margin: 0px;
    padding: 0px;
    list-style: none;
}

 

Structure

When several style definitions share some styles and are of the same family, their common styles should be defined in one place.

Example

Common message styles:

	.normalMessage,
.warningMessage,
.errorMessage {
   border-style: solid;
   border-width: 1px;
   padding: 5px;
   position: relative;
   width: 500px;
}

Specific message styles:

	.normalMessage {
   background-color: #E5EDF9;
   border-color: #4171B5;
}
	.warningMessage {
   background-color: #FFEFA7;
   border-color: #FFB30F;
}
	.errorMessage {
   background-color: #FFD1D1;
   border-color: #FF0000;
}

 

Shorthands

Use shorthand properties to keep all parts of a style type on a single line.

For example:

	margin: 5px 0 4px 10px;

Is much more efficient than:

	margin-top: 5px;
margin-right: 0;
margin-bottom: 4px;
margin-left: 10px;

Combining properties onto a single line using shorthand properties means that your CSS will be easier to understand and edit.

 

Sections

Clearly divide your stylesheet into specific sections by using a seperator like this:

	/*
========================================
           Global Styles
========================================
*/

 

 

Rules to be followed

  • If images/pictures/icons are specific to your stylesheet, put them in {your_project_name}/images/. You will then reference them from your stylesheet like this (for example)

 

	background:  url({your_project_name}/images/tab_right.gif) no-repeat right top;

 

  • It is NOT allowed to control the CSS attribute by JavaScript directly, you can get the same achievement to change the class name; if you have exception need confirm with CSS owner.

 

	document.getElementById("tagID").style.color = "red"; //This is not allowed.
 document.getElementById("tagID").className = "redFont"; //This is right way.

 

 

Comments

Comments begin with the characters "/*" and end with the characters "*/". They may occur anywhere between tokens, and their contents have no influence on the rendering. Comments may not be nested.

At the top of the css document need have these information as below:

	/* Author:
  * Purpose:
  * Contact:
  * Date Version:
  */

One good sample is:

	/* Author: Platform
  * Purpose: This doc. to initialize the layout of the framework page.
  * Contact: yshi@platform.com; Skype Id(hakula520)
  * Date Version: 06/24/09
  */

 

HTML Tag and CSS Basic Knowledge

 

External links

 

 Handle difference browser




    读后笔记:
        1、文件组织:在项目中应该创建css文件以便来保存CSS文档在自己的项目文件下,有时我们可能会使用到图片此时如果没有保存图片的文件夹应该创建一个文件夹来专门保存图片文件。
        2、命名规范:
            2.1语义语法:采用驼峰式命名规范,ex:mainContent;优化CSS代码时可以重用HTML标准标签。
            2.2命名:命名应该能够尽量清晰地描述,不应该包括风格信息。
            2.3单位:我们把px来定义元素之间的间距,pt来定义字体的大小。
            2.4间距,标点和括号:每个Style的定义之间空一行,采用适当的缩进,冒号之后加一个空格,花括号应该把属性-值包含进去。
            2.5全局的CSS定义:全局CSS定义只用在公共的CSS文件中,一旦使用全局CSS定义在项目中将会破坏其他CSS文件之间的关系。
        3、结构:当几个风格定义相同时,它们应该定义在同一个地方。
             Example

            Common message styles:

	    .normalMessage,
        .warningMessage,
        .errorMessage {
           border-style: solid;
           border-width: 1px;
           padding: 5px;
           position: relative;
           width: 500px;
        }

            Specific message styles:

	    .normalMessage {
           background-color: #E5EDF9;
           border-color: #4171B5;
        }
	    .warningMessage {
           background-color: #FFEFA7;
           border-color: #FFB30F;
        }
	    .errorMessage {
           background-color: #FFD1D1;
           border-color: #FF0000;
        }
        4、简记字符:
             margin: 5px 0 4px 10px; 和以下格式是一样的
             margin-top: 5px;
             margin-right: 0;
             margin-bottom: 4px;
             margin-left: 10px;

        5、格式:
            如果有图片存在的话,可以使用如下格式:
                background: url({your_project_name}/images/tab_right.gif) no-repeat right top;
            在CSS当中不允许直接用JavaScript控制CSS属性,可以使用如下格式:
                document.getElementById("tagID").className = "redFont"; //This is right way.
                document.getElementById("tagID").style.color = "red"; //This is not allowed.
    
        6、注释:良好的注释格式如下:
                /* A uthor: Platform
                  * Purpose: This doc. to initialize the layout of the framework page.
                    * Contact: yshi@platform.com; Skype Id(hakula520)
                      * Date Version: 08/28/2012
                      */



WEB resource reference

HTML tag specification

 

Naming/Format convention

  1. Tag name must be lowercase
  e.g.: <div> *** </div>
        <table></table>
  
  2. Tag attribute name must be lowercase, the attribute value need to use double quotation marks ""
  e.g.: <div id="" class=""></div>

  3. The Tag attribute must have one Space
  e.g.: right: <div id="" class=""></div>
        wrong: <div id=""  class=""></div> 
               <div id=""class=""></div> 
               <div id="" class=""  ></div>

  4. If the Tag content is empty, don't put blank space or Enter to there
  e.g.: right: <div id="" class=""></div> <div id="" style=""/>
               <div id="" class=""> </div> --> for render the CSS style
        wrong: <div id="" class="">    </div> or 
               <div id="" class="">
               </div>
  
  5. if the Tag has multiple levels, need to use Tab to format the code
  e.g.: right:
              <div id="baseDiv">
                  <div id="child1">
                      <div id="child1_1"></div>
                  </div>
                  <div id="child2"></div>
              </div>
         wrong:
     example1:<div id="baseDiv"><div id="child1"><div id="child1_1"></div></div><div id="child2"></div></div>
     example2:<div id="baseDiv">
              <div id="child1">
              <div id="child1_1"></div>
              </div>
              <div id="child2"></div>
              </div>
     example3:<div id="baseDiv">
                  <div id="child1"><div id="child1_1"></div>
                  </div>
                  <div id="child2"></div>
              </div> 
     etc...  

  6. If the code to long, and want to make newline, need to follow below format
     e.g.: 
        <div id="dialogBoxPanleBody" class="bd" style="overflow:hidden;">
	    <iframe class="contentIFrame" name="dialogBoxPanleBody_Iframe" id="dialogBoxPanleBody_Iframe" scrolling="auto" 
            <!-- excess area, make newline -->
            frameborder="0" ></iframe>
	    <!--div class="iFrameCover"></div-->
	    <div class="waitingPanel"></div>	
	</div>

  7. ID define policy
     The HTML tag if need to define ID, the value should reflect the functions. 
     e.g.: need a DIV to show Host Info, then the DIV ID should be: hostInfoDivId  
           (FunctionInfo + HTMLTagElementName + Id) or
           (FunctionInfo + _ +HTMLTagElementName + _ + Id) or
     Don't define a simple word as each object's id, e.g.: id1, id2 etc...
     Don't use special charactor for Id, e.g.: host-info.id
     Validate character is: letters, number, underline(_) and  dash(-)
     initial must be letters, and use lowercase
     Need to set ID for every diaplay Tag element, it can help QA make automatization test.

  8. Name define policy
     Same as ID, like: hostInfoDivName

  9. Use Close Tag for all HTML element, and don't nesting difference Tag
     right: <div></div> or <div/>
            <div>
                <table></table>
            </div>
     wrong: <div><table></table>
            <div>
                <table></div>
            </table>

 

HTML header/footer

1. add 'Doctype', use XHTML 1.0 version
   2. include 'head'
   3. must define the end Tag of </HTML>
     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
       <HTML>
       -- Header area start --
       <HEAD>
         <TITLE> New Document </TITLE>  -- define Title
         <meta http-equiv="content-type" content="text/html; charset=utf-8" /> -- Define the unicode
       </HEAD>
       -- Header area end --
       <BODY>
          <!-- Body contents  -->
       </BODY>
      </HTML>

 

DOM & JS object cross invoke convention

1. get the DOM object reference
      a. through ID, use document.getElementById("testDIVId")
      b. through Tag, use document.getElementsByTagName("Div");
      c. through Class Name, use getElementsByClass(searchClass,node,tag); 
      the JS function in: /base_common_ui/js/utilities.js
      prefer use #a, which can provide better performance

   2. use Global variable to save the common DOM object
      e.g.: formObject, we can define a Global variable: formObject = document.formName
            all object can direct use the variable.

   3. Don't create duplicate JS DOM object

 

Image in HTML

1. Add 'alt' attribute, when can't load the image, there will show help message
     e.g.: <img src="" alt=""></img>
  2. Define Size of the image, control the image size, use PX unit
     e.g.: <img src="" width="" height=""></img>
  3. Image type is: *.gif, *.jpg, *.png, don't use other type icon/images

 

JS in HTML

1. inlucde example, use 'relative' URL
      a. add 'language' and 'type' attribute
   <script language="javascript" type="text/javascript" src="/base_common_ui/js/utilities.js">  
   </script>
   2. add comments
   <!-- Inlcude the common utilities JS file, there has String Util, Browser Util etc... -->
   <script language="javascript" type="text/javascript" src="/base_common_ui/js/utilities.js">
   </script>
   3. Insert JS code in HTML, add 'language' attribute
   <script language="javascript">
       //**** source code
   </script>
   4. Don't suggest direct put JS code in JSP

 

CSS in HTML

1. example, use 'Relative' URL, add 'rel' and 'type' attributes
      <link rel="stylesheet" type="text/css" href="/base_common_ui/css/pmc_Base_FormElements.css"/>
   2. add comments
      <!-- For set Form element style -->
      <link rel="stylesheet" type="text/css" href="/base_common_ui/css/pmc_Base_FormElements.css"/>
   3. Direct put CSS in JSP page, put start|end market to there
      <!-- Define the HostInfo CSS Start -->
      <style>
      </style>
      <!-- Define the HostInfo CSS End -->
   4. Don't suggest put CSS to JSP directly

 

Iframe in HTML

1. Need to add 'id' and 'name', 'src' must set Value.
   <iframe id="pane_Messages_Body_Iframe_Id" name="pane_Messages_Body_Iframe_Name" src="***" width="100%" height="100%" scrolling="auto" frameborder="0"></iframe>
   2. Use DIV to include the iframe
   e.g.: <div id="pane_Message_Body_Id">
             <iframe id="pane_Messages_Body_Iframe_Id" ***></iframe>
         </div>
   3. Don't add CSS style attribute to HTML source directly
   e.g.: <iframe style="boder:1px;background-color:#223;"></iframe>

 

JS event

1. Execute JS function when window.onload
     a. Create self JS file, e.g.: hostInfo.js
     b. Add follow method
       var oldOnloadEvent = window.onload; 
       window.onload = function(){
        
          // inside JS function
          //execute other onload event
          oldOnloadEvent;
       }

   2. window.onunload, window.onbeforeunload, window.oncontextmenus etc...
      Don't suggest use window.onbeforeunload event

   3. if must put the JS function in HTML page, need to put JS function to <head> area, but the reference or invoke can be everywhere
   e.g.: <head>
            <script>
               //****
            </script>
         </head>

   4. Get Resoruce message from WEB Server
      a. define a message JSP file, e.g.: init_message_exc.jsp
         <script> 
             var REBOOT_HOST_SUCCESS_MES = '<s:text name="reboot.host.success.message"/>';
         </script>
      b. include this JSP in <head> area
      c. Use Struts Tag to load all Resource properties info
      Example:

   5. If must put JS code to HTML BODY area, need to add comments
   e.g.:
       <!--  Get Viewport configuration start -->
       <script>
           // Use JSTL, Struts Tag cycle output the JS code
       </script>
       <!--  Get Viewport configuration end -->

 

Scroll bar control

1. window scrollbar
      Don't control the window scrollbar inside the HTML page

   2. window.document.body scrollbar
      <!-- For IE -->
      <body scroll="no">
      </body>
      <!-- For Firefox -->
      <style>
         .body{
               overflow:hidden;
         }
      </style>
    
    3. DIV scrollbar
       Use CSS control
    Notice: don't control the body and DIV scrollbar together, otherwise there will show double scrollbar

    4. overflow-x and overflow-y, control the scrollbar x|y show|hide

    5. don't reset the scroll bar style inside the HTML page

 

Other plugin in HTML

1. Applet include
       <applet code="Bubbles.class" width="350px" height="350px">
            Java applet that draws animated bubbles.
       </applet>
    reference: http://www.w3school.com.cn/tags/tag_applet.asp

    2. Flash include
       <object width="550" height="400">
          <param name="movie" value="somefilename.swf">
          <embed src="somefilename.swf" width="550px" height="400px">
          </embed>
       </object>
    reference: http://www.w3schools.com/flash/flash_inhtml.asp

    3. Image area control
       <img src ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap" />

       <map name="planetmap">
           <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" />
           <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury" />
           <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus" />
       </map>
    reference:http://www.w3schools.com/tags/tag_area.asp

HTML comments

1. When the function exceed 50 line, need to add comments
    e.g.: 
        <!-- Display VM overview Common part start -->
        <div>
           //*****
        </div>
        <!-- Display VM overview Common part end -->
    2. The Comments can't less than 20 character
    3. For indecate the component area, need to add start|end mark
    4. Use HTML comment format

 

Forbidden Tag Usage

1. <br>, if you want make new line, use <p> tag, the space size can be controlled by CSS
    2. <center>, use CSS to control
    3.   use CSS to set
    4. <b>, use CSS to control
       e.g.:
            <div class="divCSS"> Test Text </div>
        test.css
            div.divCSS{
              font-size:12px;
              font-weight: bold;
            }
    5. <h1> -- <h6>
       Use 'font-size' to control it
    6. <hr>, use DIV instead of it
       e.g.:
            <div class="divCSS"></div>
         test.css
            div.divCSS{
               width:100%;
               height:1px;
               background-color:#000000;
            }
    7. <button> and <input type="button">
       Suggest use button tag, for consistent the Look & Feel and the interaction
    -- Detail please refer the CSS coding convention --
    8. <strong></strong>,use CSS to control, SAME as <b>
    9. <em></em>,use CSS to control
       e.g.: <div class="divCSS"></div>
         test.css
            div.divCSS{
              font-style: italic;
            }
    10. <font></font>,use CSS to control
    11. <big></big>,use CSS to control
    12. <small></small>,use CSS to control
    13. <layer></layer>,use <div> tag + CSS to control

 

Wrong Usage

1. <a href="#" οnclick=""></a>
      if put Java script event on <a> object, then add 'onclick' attribute, and don't use href="#"
      right usage is:
      <a href="" οnclick="JSFunction(); return false;"></a>
 
    
 
    
    读后笔记:
        1、命名格式规则:
            1.1、标签名必须是小写;
            1.2、标签属性名必须小写,对应的属性值必须用“ ”双引号包围;
            1.3、标签属性之间有一个空格;
            1.4、如果标签的内容为空,最好不要使用回车或者空格;
            1.5、如果标签有两级以上,需要使用适当的缩进。
            1.6、如果代码太长,需要跨行;
            1.7、ID/Name定义规则:如果需要定义ID/Name则该ID/Name要能够反应其功能。
                比如:need a DIV to show Host Info, then the DIV ID should be: hostInfoDivId                
                (FunctionInfo + HTMLTagElementName + Id) or
                (FunctionInfo + _ +HTMLTagElementName + _ + Id) 
        
        2、HTML页眉和页脚:
            2.1、在页眉增加'Doctype',使用XHTML 1.0 version
            2.2、包括'head'标签,在最后记得加上</html>

        3、image在HTML使用规则:
            3.1、增加'alt'属性,如果图片不能加载时,将会显示帮助信息;
        e.g.: <img src="" alt=""></img>
            3.2、定义图片的大小,使用px作为单位;            
                e.g.: <img src="" width="" height=""></img>
            3.3、图片格式包括:*.gif,*.jpg,*.png;
        
        4、JavaScript在HTML使用规则:
            4.1、添加'language'、'type'属性:<script language="javascript" type="text/javascript" src="/base_common_ui/js/utilities.js">   </script>;
            4.2、添加注释;
            4.3、添加JavaScript到HTML,记得添加'language'属性;
            4.4、不建议直接把JavaScript代码直接放在JSP页面当中;

        5、CSS在HTML使用规则:
            5.1、使用相对URL,包含'rel'和'type'属性;<link rel="stylesheet" type="text/css" href="/base_common_ui/css/pmc_Base_FormElements.css"/>;
            5.2、添加注释;
            5.3、在JSP页面当中直接使用CSS时,应该添加开始和结束标志。<style> </style>;
            5.4、不建议直接把CSS代码直接放在JSP页面当中;

        6、内联框架在HTML使用规则:
            6.1、需要'id'、'name'、'src'属性,而且必须设值:
                <iframe id="pane_Messages_Body_Iframe_Id" name="pane_Messages_Body_Iframe_Name" src                    ="***" width="100%" height="100%" scrolling="auto" frameborder="0"></iframe>
            6.2、可以使用DIV包含iframe:
                e.g.: <div id="pane_Message_Body_Id">
                         <iframe id="pane_Messages_Body_Iframe_Id" ***></iframe>
                     </div>
            6.3、不要直接在HTML源中添加CSS样式属性

        7、JavaScript事件:
            7.1、当window.onload执行JS函数:
                    7.1.1创建JS自身文件,eg:hostInfo.js
                    7.1.2增加如下方法:
                        var oldOnloadEvent = window.onload;
                        window.onload = function(){
                            //inside JS function
                            //execute other onload event
                            oldOnloadEvent;
                        }
            7.2、window.onunload, window.onbeforeunload, window.oncontextmenus etc...不建议使用window.onbeforeunload;
            7.3、如果必须把JS函数嵌入在HTML页面中,需要把函数放在<head>区域里面,但参考或者调用可以无处不在;
            7.4、在HTML页面中嵌入JS,最好添加注释;

        8、滚动条控制:
            8.1、不要把控制滚动条的窗口放在HTML里面;
            8.2、overflow-x和overflow-y,这两个控制滚动条x|y show|hide;
            8.3、不要重置滚动条的样式在HTML里面;
            8.4、别把body和DIV的滚动条放在一起,否则将会同时显示两个滚动条;
            8.5、window.document.body滚动条例子:
                    <!--For IE-->
                    <body scoll="no">
                    </body>
                    <!--For Firefox-->
                    <style>
                        .body{
                                    overflow:hidder;
                        }
                    </style>

        9、其它插件在HTML使用规则:
            9.1、Applet include:                
                <applet code="Bubbles.class" width="350px" height="350px">
                    Java applet that draws animated bubbles.
               </applet>
                reference: http://www.w3school.com.cn/tags/tag_applet.asp
            9.2、Flash include:
                <object width="550" height="400">
                  <param name="movie" value="somefilename.swf">
                  <embed src="somefilename.swf" width="550px" height="400px">
                  </embed>
               </object>
                reference: http://www.w3schools.com/flash/flash_inhtml.asp
            9.3、Image area control:    
       <img src ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap" />
               <map name="planetmap">
                   <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" />
                   <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury" />
                   <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus" />
               </map>
                reference:http://www.w3schools.com/tags/tag_area.asp

        10、HTML注释:
            如果函数代码超过50行,最好为其添加一定的注释方便他人阅读。

        11、被禁止的Tag:
            11.1、<br>,如果想另起一行可以使用<p>标签来实现;
            11.2、<h1> -- <h6>可以使用'font-size'来替换;
            11.3、<hr>可以使用DIV来替换;
            11.4、

Summary

This is a set of coding conventions and rules for use in JavaScript programming.
1. Need to make consistent code style
2. Provide better code usage

 

File Directory Definition

1. Create File rule
    a. each feature can create single JS file
    b. if some function has been used by multiple features, then make it as Common/Public function
    c. If the function has been used by multiple product, put it to Base_common_ui/common_ui directory
 2. JS file comments
    a. for create new JS file, you need to put the file usage description on the title
       e.g.: 
          /**
            * @Product Version:
            * @Author:
            * @Date:
            * @Description: JS class description; dependency; reference etc...
            */
 3. Common file Dir
    // it's PMC 2.0 common APP, all PMC Framework provide Common JS should be put to there
    // CVS location: /cvs/CVS/gui/shared/ui/
    base_common_ui--|
                    |js--|
                         |common.js
                         |stringUnit.js
                         |cookies.js ...
                    |css--
                    |images
                    |etc...
    // it's PMC 1.0 common APP, current LSF, Symphony, Cloud, PERF GUI has used it, all update should be put to there
    // CVS location: /cvs/CVS/gui/common/common_ui/
    common_ui--|
               |js--|
                    |common.js ...
               |css--
               |images
               |etc...
 4. Each component file Dir
    e.g.:
    vmgui --|
            |js            ---> it's the WEB APP common JS DIR
            |images
            |css
            |host --|      ---> it's the feature component file DIR
                    |--js  ---> all internal JS file should be put to here
                    |--css
                    |--images
 5. For complex component, you can define intenral folder
   e.g.:
   base_common_ui --|
                    |js --|
                          | Calendar --|
                                       |--js
                                       |--images
                                       |--css
 6. Define the license txt file in Common DIR
   e.g.: 
   base_common_ui --|
                    |js --|
                          | platform_license.txt

 

Naming/Formatting

* Naming

1. Names should be formed from the 26 upper and lower case letters (A .. Z, a .. z), the 10 digits (0 .. 9), and _ (underbar).
    Avoid use of international characters because they may not read well or be understood everywhere. Do not use $ 
    (dollar sign) or \  (backslash) in names.
    Right: 
      Function Name: setVMRequestInfo() --> Normal function name first character should be lower case.
      Variable Name: var vmName = null;
    Wrong: 
      Function Name: 
                    // it's special and international characters, avoid use it
                     Submit(); Test();
      Variable Name: 
                    // it's JS internal characters, don't use it
                    var string = null;
                    // Don't use special characters
                    var test_$_name = null; var test_/\_name = null;
2. Do not use _ (underbar) as the first character of a name. It is sometimes used to indicate privacy, 
    but it does not actually provide privacy. If privacy is important, use the forms that provide private members. 
    Avoid conventions that demonstrate a lack of competence.
    Wrong:
       // the userName is public variable, put the _ in first character is wrong 
       var _userName = null; 
    Most variables and functions should start with a lower case letter.
    Right: 
       var userName = null;
    Wrong: 
       var UserName = null;
3. Constructor functions which must be used with the new prefix should start with a capital letter. 
    JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted. 
    Bad things can happen if new is not used, so the capitalization convention is the only defense we have.
    Right:
        funcation checkStr();
    Don't use _- in Function Name.
    e.g.:
        function check-Str(); or check_Str();
4. JS class file name capital letter should be lowercase. Only allow letter, number, _, -
    Right:
         pmc_navigation_tree-debug.js --> the last String can be removed '-debug', it indecate the JS file type.
         host_overview-info.js
    Wrong:
         PMC_navigation_tree.js
         _HostOverView.js
         hostOverView.JS
5. Global final-static variables should be in all caps. (JavaScript does not have macros or constants, 
    so there isn't much point in using all caps to signify features that JavaScript doesn't have.)
    Right: 
       var TOKEN = "";
    wrong:
       var token = ""; var Token = "";
6. The key String of 'function' must be lowercase, don't write it as: Function, FUNCATION etc...
7. The key String of 'var' must be lowercase, don't write it as: VAR, Var etc...

 

 8. All window event expression must be lowsercase
    onclick, onchange, ondbclick, onmouseover, onmouseout, onkeypress, onkyedown, onkeyup etc...
    Wrong:
          Onclick, OnClick, ONCLICK etc...
 9. All DOM key String must be lowsercase
    e.g.: window, document, location, form, iframe, frames, body, html etc...
    Wrong:
          Window, WINDOW etc...

* Code Formatting

1. Indentation
    a. Use Tab key to format each line.
    b. Must append ;(semicolon) for every line, don't put blank-space before it.
    c. Don't put new Line for {
    d. Must put new Line for }
    e. use one blank-space before {
    Right: 
          function myFristFun() {
            //***
            var initVar = null;
          }
          var myFristFun = function() {
            //***
          }
    Wrong:
          function myFristFun()
          {
             //***
             var initVar = null
          }
          function myFristFun()
          {
             //***
             var initVar
          }
          function myFristFun()
          {  var initVar }
         etc...
     e. use one blank-space between key of 'function' and 'functon name'.
        e.g.: function myFristFun() {
        Wrong:
              function   myFunctionFun(){
              function myFunctionFun (){
     f. For multiple parameters, put one blank-space to format them, and the first letter should be lower case
        e.g.:
           Right:
            function myTestFunction(userName, password, desc){
            }
           Wrong:
            function myTestFunction(userName,password,  desc){
            }
            function myTestFunction(UserName, Password,  Desc){
            }
       #Notice: about those statement expression, apply same rule. e.g.: for, if, while etc...   
     g. Append one blank-space before ( and end )
        e.g.:
           Right:
             if (a == 1) {
             } 
             for (var i = 0; i < 10; i++) {
             }
           Wrong:
             if(a == 1) {
             }  
             if( a == 1){
             }
             if ( a == 1)  {
             }
             etc..    
 2. Line Length 
    Avoid lines longer than 80 characters. When a statement will not fit on a single line, it may be necessary to break it.
    Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a 
    copy-paste error will be masked by semicolon insertion. The next line should be indented 1 Tab.
 3. Comments
    a. Function comments
       put the function description on each 'Function statement' title
       e.g.:
         /**
           * @Description:
           * @parameter: -- Optional
           * @See: -- Optional
           * @return:-- Optional
           */
          function loginChecking(formObj){
            //***
          }
    b. Inside the Function comments
       For inside coding comments
       e.g.:
          function loginChecking(formObj){
            //Get the 'user name' Form input element obejct
            var userNameInput = formObj.userName;
            //Validate the userNameInput whether include error/invalidate character
            if(validateStr(userNameInput.value)){
               //all character is validate
               //put the handle
            }else{
               //found invalidate character
               //put the handle
            }
          }
    c. Internal function comments
       e.g.:
         function loginChecking(formObj){
             var userNameInput = formObj.userName;
             var passwordInput = formObj.password;
           /**
             * @description: It's inside private function, you can use it within this function
             * @return: true|false
             *          true: the String is validated
             *          false: the String value include invalidte character
             */
             this.checkingStr = function(strValue){
                 //put the detail logic
             }
             //use the private method
             if(this.checkingStr(userNameInput )){
                //do something
             }else{
             }
             //use the private method
             if(this.checkingStr(passwordInput )){
                //do something
             }else{
             }
         }
     d. Comment requirements
        a. all function need to put the comments
        b. all if/while/for/switch expression need to put comments
        c. for complex handle, need to put the comments
        d. the code handle excess 20 line, need to put comments

 

Class file create rule

1. All functions need to put to external JS file, don't put JS function in HTML/JSP page directly
 2. If the 'Method' has been used by many place for this feature component, put it to /$COMPONENT/$FEATURENAME/js/***.js
 3. If the 'Method' is a common handle for whole project, put it to /$COMPONENT/js/***.js
 4. If the 'Method' will be used by another WEB APP, or provide by PMC framework need to put to: /base_common_ui/js/***.js
 5. How to set the Class file name
    a. For 'Feature' level JS class, use the Feature Name as prefix should be better
       e.g.: host_overview.js
           //all Row action, dialog function will be put to there. etc...
    b. For 'Component' and 'APP-common' level JS class, need use the general name
       e.g.: string_unit.js
             dom_html.js
             cookies.js
             dom_xml.js
             drag_drop.js
             etc...
 6. Don't put 'common.js' for either project

 

Function define Rule

1. Don't allow put JS code to HTML page
    e.g.: <a href="" οnclick="if(**){alert('test')};">
 2. If the JS handle excess 5 line, need to create function.
    Exception: just single line handle. e.g.: window.title = "It's first testing";
    For static execute JS code, create JS class to init them.
e.g.: 
           var staticDOMManager = {
              "domainDivObj":document.getElementById("domainDiv"),
	      "windowCoverObj":document.getElementById("windowCover"),
	      "desktopCoverObj":document.getElementById("desktopCover"),
	      "preferenceCoverObj":document.getElementById("preferenceCover")
           }
3. When we need a Bean object to store the JS/HTML DOM object then create JS function to implement it
    e.g.:
    /*
     * @description: create User info bean
     *               we can use it to operate the user properties/list page
     * @usage:
     *        var newUserInfoBean = new UserInfo();
     *            newUserInfoBean.setUserName("testUser");
     */
    function UserInfo(){
       this.userName = null;
       this.password = null;
       this.desc = null;
       /*
        * for set the 'userName' property
        */
       this.setUserName = function(userName){
          this.userName = userName
       }
       //****
    }
 4. If you will create multiple function for solve one kind problem, need to create a function object. Same as: java OOP
    e.g.: for create/control status bar
    JS file name: pmc_status_bar_mgr.js
    /*
     *@description:Create function object
     *@return: no return
     *@usage: once include this js, you can use: 
     *             pmcStatusBarMgr.init();   //init the bar objects
     *             pmcStatusBarMgr.barDragDropIcon.***  //operation drag-drop
     *             pmcStatusBarMgr.destroy();    //release memory
     *             pmcStatusBarMgr = null;
     */
    var pmcStatusBarMgr = {};
    {
        //create the status bar properties
        this.bodyDiv = "";
        //***
        /*
         * @description: init the status bar data/HTML element/event
         * @parameter: no
         * @return: no
         */
        this.init = function(){
           //get data
           //generate HTML
           //append JS events
           //render JS events
        }
        this.initDragDrop = function(){
        }
        this.generateHTML = function(){
        }
        this.getBarData = function(){
        }
        /*** More functions ***/
        
        this.destroy = function(){
           //clear up memory
        }
    }
    Bad usage: use split function, we can't better to understand the function detail meanings.
    function createStatusBar(){
    }
    function initStatusBarEvents(){
    }

 

New variable

1. Need to give init value.
 Right: var testVar = null;
        var testVar = "";
 Wrong:
        var testVar;
        var testVar = ${userName}; //if the userName can't return value, here will happend JS ERROR. it variable can't be init.
2. Don't use duplicate variable name.
 e.g.: Define global variable: var testVar = "";
       Create a Function:
       function myFirstFun(){
         var testVar = null;   --> It's wrong;
         testVar = "123";      --> reset it will change the Global variable value.
       }
3. Need to use 'var' when define new private variable.
 e.g.:
      function myFirstFun(){
         var privateVariable = "";
         privateVariable_1 = "";     --> It's wrong
      }
4. Need to clear the memory for Array object, for complex JS application, we need to provide such handle.
    If you just use it once and in simple JSP/HTML page, don't need to put this handle.
 e.g.:
      var testArray = function(){
          this.myArray = [****];
          this.myArrayObj = {*****};
          /*
           *@Descripton: provide destory method for release all object
           *@return: no return;
           *If happen exception, don't throw the message.
           */
          this.destroy = function(){
             //use for cycle to clear the memeory
             for(){
                this.myArray[i] = null;     --> set the array every item to 'null', release memory
             }
             this.myArray = null;  --> set the array object to 'null', cut all Stack-address connection
             delete this.myArray;  --> delete this object
             //remove object of 'this.myArrayObj'
             //***
          }
      }

 

Operate DOM object

For WEB 2.0, we have too many requirement that through JS object to operate the HTML DOM object.

For avoid the preformance and memory leak. W3C website

General rule:

1. Avoid cross invoke/reference for difference DOM/JS object
    Reference: http://www.javascriptkit.com/javatutors/closuresleak/index.shtml
 
 2. Avoid use JS to create HTML DOM object
    e.g.:
         document.createElement("<div onClick='foo()'>");
    better way is:
         parentDIVObject.innerHTML = "<div onClick='foo()'>";
 
 3. Use DOM Style attribute
    a. set 'display'
    e.g.:
         buttonDivObj.style.display = "none";
         buttonDivObj.style.display = "block";
         buttonDivObj.style.display = "";
         //about the "block" or empty "", they indecate difference setting for each browser
         // the "block" will avaliable when control a "DIV" element, for other HTML element, you can use empty "".
    
    b. If you want update DIV's background-image, better way is define a regular icon name
    e.g.:
         vm_close.gif vm_open.gif vm_restart.gif
         //use JS to reset it
         var vmStatusOld = "close|open|restart";
         var vmStatusNew = "close|open|restart";
         //create internal temp variable for operate this DIV's style attribute.
         var _vmStyle = vmDivObj.style;
         //just use 'replace' expression, don't hardcode image URL to there
         vmStyle.backgroundImage = vmStyle.backgroundImage.replace(vmStatusOld,vmStatusNew);
    Need more discussion, Yang Shi suggest use CSS to implement it.
4. if CSS class can solve the problem don't use JS to handle it.
    e.g.: when onmouseover update the DIV's background-image/color
    Right:
         <a>
             <div></div>
         </a>
         Create CSS for the a:
            a.hover;      --> set highlight image, same as: onmouseover.
            a.active; 
            a.link;       --> set default image
            a.visited
    Wrong:
         <a οnmοuseοver="update image" οnmοuseοut="restore image" >
             <div></div>
         </a>

 

Quotation marks

1. single quotation marks
    For define the String value, e.g.: It's first example
 2. double quotation marks
    For define the String object, e.g.: var userName = "Test User";
 3. For mix condition, the both sides mark must be ""
    Right:
          var userName = "I'm tester";
          var machineInfo = "It's my team machine, the name is \"MasterHost\";";
    Wrong:
          var userName = 'I\'m tester';
          var machineInfo = 'It\'s my team machine, the name is "MasterHost";';
 4. Don't pass the quotation in URL, if have to use it, use encodeURIComponent(url) to translate it.

 

Statements

1. Simple Statements

Each line should contain at most one statement. Put a ; (semicolon) at the end of every simple statement. 
 Note that an assignment statement which is assigning a function literal or object literal is still an assignment 
 statement and must end with a semicolon.
 JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence 
 of semicolon insertion. The only expressions that should be used as statements are assignments and invocations.

2. Compound Statements

Compound statements are statements that contain lists of statements enclosed in { } (curly braces).
   * The enclosed statements should be indented four more spaces.
   * The { (left curly brace) should be at the end of the line that begins the compound statement.
   * The } (right curly brace) should begin a line and be indented to align with the beginning of the line containing the 
     matching { (left curly brace).
   * Braces should be used around all statements, even single statements, when they are part of a control structure, 
     such as an if or for statement. This makes it easier to add statements without accidentally introducing bugs.

3. Labels

  Statement labels are optional. Only these statements should be labeled: while, do, for, switch.

4. return Statement

A return statement with a value should not use ( ) (parentheses) around the value. The return value expression must start 
  on the same line as the return keyword in order to avoid semicolon insertion.

5. if Statement

The if class of statements should have the following form:
   if (condition) {
       statements
   }
   
   if (condition) {
       statements
   } else {
       statements
   }
   
   if (condition) {
       statements
   } else if (condition) {
       statements
   } else {
       statements
   }

6. for Statement

A for class of statements should have the following form:
   for (initialization; condition; update) {
       statements
   }
   for (variable in object) {
       if (filter) {
           statements
       }
   }
The first form should be used with arrays and with loops of a predeterminable number of iterations.  
  The second form should be used with objects. Be aware that members that are added to the prototype of the object will be 
  included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true 
  members of the object:
   for (variable in object) {
       if (object.hasOwnProperty(variable)) {
           statements
       }
   }

7. while Statement

A while statement should have the following form:
   while (condition) {
       statements
   }

8. do Statement

A do statement should have the following form:
   do {
       statements
   } while (condition);
   Unlike the other compound statements, the do statement always ends with a ; (semicolon).

9. switch Statement

A switch statement should have the following form:
   switch (expression) {
   case expression:
       statements
   default:
       statements
   }
Each case is aligned with the switch. This avoids over-indentation.
  Each group of statements (except the default) should end with break, return, or throw. Do not fall through.

10. try Statement

The try class of statements should have the following form:
   try {
       statements
   } catch (variable) {
       statements
   }
   try {
       statements
   } catch (variable) {
       statements
   } finally {
       statements
   }

11. continue Statement

Avoid use of the continue statement. It tends to obscure the control flow of the function.

12. with Statement

The with statement should not be used.

 

Bonus Suggestions

1. {} and []

Use {} instead of new Object(). Use [] instead of new Array().
 Use arrays when the member names would be sequential integers. 
 Use objects when the member names are arbitrary strings or names. 

2. , (comma) Operator

Avoid the use of the comma operator except for very disciplined use in the control part of for statements. 
 (This does not apply to the comma separator, which is used in object literals, array literals, var statements, 
 and parameter lists.)  
 e.g.:
    Wrong:
       var testA = null, testB = 123; --> we should define them as: var testA = null; var testB = 123;
       

3. Block Scope

In JavaScript blocks do not have scope. Only functions have scope. Do not use blocks except as required by the 
compound statements. 
e.g.:
    Wrong:
    {
       /**
       * VM overview page init those parameters
       */
       var initDOMObject = ""; // --- generate the DOM object
       window.onload = function(){
           //**** detail handle
       }
       //append more JS code
    }
    Right:
    var overViewInitMgr = function() {
         this.initDOM = function() {
           //append the JS code
         }
         this.initEvent = function(){
           //append the JS code
         }
         //more function
    }

4. Assignment Expressions

Avoid doing assignments in the condition part of if and while statements.
 Is
   if (a = b) {
 a correct statement? Or was
   if (a == b) {
 intended? Avoid constructs that cannot easily be determined to be correct. 

5. === and !== Operators.

It is almost always better to use the === and !== operators. The == and != operators do type coercion. In particular, 
 do not use == to compare against falsy values. 

6. Confusing Pluses and Minuses

Be careful to not follow a + with + or ++. This pattern can be confusing. Insert parens between them to make your 
 intention clear.
   total = subtotal + +myInput.value;
 is better written as
   total = subtotal + (+myInput.value);
 so that the + + is not misread as ++. 

7. eval is Evil

The eval function is the most misused feature of JavaScript. Avoid it.
 eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.

8. try/catch

Avoid use try/catch for each JS expression.
 If must use it, need to handle the exception.
 e.g.:
 try{
    //handle
 }catch(e){
    //put the exception message to log.
    //e.g.: use Yahoo.log
    YAHOO.log("Function Name:**; Error message:" + e.message);
 }

9. setTimeout and setInterval

Avoid use 'setInterval', due to we can't control it easily.
  Use setTimeout to implement same function.
  e.g.:
  var timeoutObj = null;
  function testIntervalFun(){
     //detail handle
     ...
     //create the 'timeout' handle
     //when all condition ok, then keep the 'timeout' function
     if(ok){
         timeoutObj = setTimeout("testIntervalFun()", 1000);
     }
     //if happen exception, we can stop the time out
     if(exsitException){
         clearTimeout(timeoutObj );  
     }
  }
  //start the 'timeout' handle
  timeoutObj = setTimeout("testIntervalFun()", 1000);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值