The java code convention document:
- English Address: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
- Chinese Address: http://www.huihoo.org/code/java_code_conventions.htm
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.
- UserService: This is interface defines some exposed method.
- UserServiceRealImpl: This is real implementation class that invoke back-end api or operate database.
- 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:
- Get the data from Service layer, and set it to one or more action properties.
- Organize data from front-end form for service and invoke service method to do action.
- 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.
- Do not put user authentication and authorization code in action class. That should be in Filter class.
- 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.
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.
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
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;
}
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.JS5. 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. LabelsStatement 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);