Java Development experience Sharing

Source: Internet
Author: User
Tags finally block garbage collection lowercase mkdir knowledge base stringbuffer

Development experience Sharing one, coding

1. Restrain yourself, standardize coding habits

Adequate code annotations, standard indentation formats, and attention to naming conventions. Reference to "Development Management code"

"Looking" Professional can promote code quality. The more unsightly the code, the worse it will be in its evolution. Because when you see the code that you want to bugfix is very messy, then in the bugfix of the general will also be a quickie. One method has 400 lines, and when you modify this method you don't care to add dozens of lines of code. Because it looks very bad, it is very bad, I do not need to beautify it. Conversely, if the code to be changed is neat and tidy, then the modifier will be more careful.

2. Avoidance of lengthy methods and classes

The method should be designed as a concise, functional unit, using it to describe and implement a discontinuous class interface section. Ideally, the method should be concise. If the length is large, consider dividing it into a shorter method in some way. This also makes it easy to reuse code within the class (sometimes the method must be very large, but they should still do just the same thing).

3. Do not write useless data to standard output

System.out.println (); This statement in the program can be seen everywhere, are used in debugging, in the process of the official run also did not remove it, the result is that the log has a large number of useless data, not only makes the log difficult to analyze, but also increased the cost of the system.

To debug the available LogWriter, set the Web-inf/ini/merpserver.ini loglevel to 4

4. Note the parameter checksum before calling the method to determine whether the parameter is empty or meaningless

5. Check whether the object is empty before using the object

if (names!=null&&names.length>0) {

string[] NameArray = Names.split (', ');

}

if (useren!=null) {

String name = Useren.getname ();

}

6. Avoid excessive and frequent creation of Java objects

Try to avoid the methods that are frequently invoked, the new object in the loop, because the system not only takes time to create objects, but also takes time to garbage collection and processing of these objects, in the range we can control to maximize the reuse of objects, preferably with a basic data type or array to replace the object.

7. Avoid arbitrary use of class member variables as far as possible

When an object is defined as a reference to a STATAIC variable, the GC usually does not reclaim the memory that the object occupies. At this point the lifecycle of the class member variable is synchronized with the class, and if the class is not unloaded, the object will reside in memory until the program terminates

8. Reduce the repeated calculation of variables

Such as

for (int i=0;i<list.size (); i++)

should read

for (int i=0,len=list.size (); i<len;i++)

And in the loop should avoid the use of complex expressions, in the loop, the loop condition will be repeatedly computed, if not the use of complex expressions, and the value of the cyclic condition is unchanged, the program will run faster

9. Avoid unnecessary creation of objects

Such as

A A = new A ();

if (i==1) {

List.add (a);

}

should read

if (i==1) {

A A = new A ();

List.add (a);

}

10. In principle the circulation inside does not declare the object, all in the circulation outside declares

for (int i=0;i<size;i++) {

String title = "title";

}

To

String title = null;

for (int i=0;i<size;i++) {

title = "caption";

}

11. Try to release resources in finally blocks

The resources used in the program should be freed to avoid resource leaks. It's better to do it in the finally block. The finally block is always executed, regardless of the outcome of the program execution, to ensure that the resource is properly closed.

12. Using StringBuilder and StringBuffer for string concatenation

StringBuffer provides a synchronization mechanism, so concurrent thread access is thread-safe and is suitable for multithreading.

StringBuilder does not mention synchronization mechanism, so thread is not safe, suitable for single thread, but if it is single-threaded, it is faster than StringBuffer.

13. Traverse HashMap using EntrySet

When you need to traverse HashMap, please try to use EntrySet, instead of using keyset,entryset more efficient than keyset, actually use EntrySet is only need to traverse a hash, The mapping of key and value into the entry, and then take it, and keyset need two times to traverse the hash, the first time to take all the key, the second time with key to take out the corresponding value.

Iterator iter = Hashmap.entryset (). iterator ();

while (Iter.hasnext ()) {

Map.entry Entry = (map.entry) iter.next ();

String key = String.valueof (Entry.getkey ());

String val = string.valueof (Entry.getvalue ());

}

14. Cache frequently used objects as much as possible

Caching frequently used objects as much as possible, using arrays, or hashmap containers for caching, can cause the system to consume too much cache and degrade performance.

Recommended reference to the development Guide, using the Ehcache

15. Use a unified tool class

Using the common methods in Hanwebcommon.jar, refer to the development guide

Use a tool class that already exists in your project, and do not repeat the classes and methods that create the function approximation if necessary to extend

such as: Receive parameters using Convert.getparameter (request, parameter name);

16. Reduce unnecessary space and blank lines, refer to the Development management specification

Do not show a yellow warning in Java code. Annotate or delete unused variables; Remove excess import when saving;

18. Reception STIRNG type parameters for cross-site scripting and SQL injection filtering

Convert.getparameter (Request, "keyword", "", true,true);

19. Do not implement the business logic in the JSP, put it into the class to complete

Layered design realizes the decoupling between software; facilitate the division of labor, ease of maintenance, improve the reuse of software components, easy to replace a product, such as the persistence layer with hibernate, need to replace the product with TopLink, you do not need to change other business code, directly to the configuration of a change; facilitate the expansion of product features , easy to adapt to the changing needs of users.

20. Avoid using Try-catch blocks in the loop body, preferably using try--catch blocks outside the loop to improve system

Oracle Large-segment operations

First insert an empty CLOB type Empty_clob (), and then update the CLOB field individually

Insertsql insql = new Insertsql (strtablename);

Insql.addstring ("Vc_name", name);

if (("Oracle"). Equals (Sysinit.getm_strdb_type ()) {

Insql.addclob ("vc_adress");

Insql.addclob ("Vc_path");

}else{

Insql.addstring ("vc_adress", address);

Insql.addstring ("Vc_path", Path);

}

Boolean bl = Manager.doexcute (Strappid, Insql.getsql ());

if (BL) {

if (("Oracle"). Equals (Sysinit.getm_strdb_type ()) {

String[] Strfieldvalue = {address, path};

String[] strFieldName ={"vc_adress", "Vc_path"};

Manager.doclob (Strappid, strFieldName, Strfieldvalue, strTableName, "WHERE i_id =" + GetMaxID ());

}

}

22. Use of unified <! DOCTYPE>, ensure page compatibility under different browsers

Recommended Use:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

The HTML structure should be complete and correct.

Standard HTML Document structure:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>

<title>insert title here</title>

......

<body>

......

</body>

Other:

<ul>

<li>......</li>

<li>......</li>

</ul>

<table>

<tr>

<td>......</td>

</tr>

</table>

HTML tags to complete

Label name and attributes uniform use lowercase, labels to appear in pairs, such as:

<div id= "Search" >.........</div>

is not used for labels that contain content, you can end with a "/" tag at the end of the label, such as:

<input type= "text" name= "username" value= "Tony"/>

<br/>

25. Tag attribute values must be enclosed in double quotes

The standard indentation is used in HTML code

27. Script Each statement to end with a semicolon

28. A style that is unique and does not need to be reused, using inline styles:

<div style= "title" > title <div>

A style that can be reused, defined in a style sheet:

<li class= "menu" > Menus </li>

Styles used within a page, using inline style sheets:

<style type= "Text/css" >

. menu{

Color:black;

font-size:13px;

}

</style>

Styles that are common to multiple pages use a link to an external style sheet:

<link href= ". /global.css "rel=" stylesheet "type=" Text/css "/>"

29. Script functions used within the page, defined in the head:

<script type= "Text/javascript" >

function Checkform () {

......

}

</script>

Repeated script functions or more code scripts, written to the outside of this script file, in the head link:

<script type= "Text/javascript" src= ". /checkform.js "/>

Scripts that do not affect the presentation of the page itself can be considered at the end of the body call, such as AD code:

......

<script type= "Text/javascript" src= ". /adv.js "/>

</body>

30. Style unification, save the code to be formatted, CTRL+SHIFT+F

31. Nurturance the consciousness of the procedure optimization

Now we often encounter a problem is that the program in the development phase, the implementation of the completely normal, to find a test staff test is no problem, but one to the line, performance immediately out of the question, the speed of running like a snail, customers unbearable, why. Simply put, the developer Self-Test, estimates also on a few data, testers test, estimated also on hundreds of data, general program code, in this order of magnitude, performance bottlenecks simply do not appear. But after the line, the customer's data generally rise to level 10,000, if the program code does not do the subtle points are very rigorous, the problem immediately exposed.

second, the database

1. Reserved words in SQL statements, function names to uppercase, indicate, field name all lowercase

For example: SELECT vc_name,vc_sex,i_age from user WHERE i_id = I_type = 2

2. Use standard SQL statements to prevent database compatibility issues

3. Loop inside (including loop call method) Avoid too much manipulation of the database

4. Select the most efficient table name order

The ORACLE parser processes the table names in the FROM clause in Right-to-left order, the last table (driving table), which is written in the FROM clause, is processed first, and in the case where multiple tables are included in the FROM clause, the table with the fewest number of record bars must be selected as the underlying table. If you have more than 3 table join queries, you will need to select the Crosstab table (intersection table) as the underlying table, which is the table referenced by the other tables

5. Note The order of joins in the WHERE clause

Oracle parses the WHERE clause in a bottom-up order, according to which the connection between the tables must be written before the other where conditions, and the conditions that can filter out the maximum number of records must be written at the end of the WHERE clause

6. Avoid using * in SELECT clause

Oracle converts ' * ' to all column names in the parsing process, which is done by querying the data dictionary, which means more time will be spent

7. Reduce the number of access to the database, as much as possible to manipulate the database, such as bulk deletion

Oracle does a lot of work internally: Parsing SQL statements, estimating index utilization, binding variables, reading chunks, etc.

8. Avoid using In,not in,or or having in the WHERE clause

You can use exist and not exist instead of in and in

9. Replace the HAVING clause with the WHERE clause

Avoid the HAVING clause, which will filter the result set only after all records have been retrieved. This processing requires sorting, totals, and so on. If you can limit the number of records through the WHERE clause, you can reduce the overhead.

10. Good Database Services

A transaction is a series of actions performed as a single logical unit of work. By combining a set of related actions into a unit that is either fully successful or all failed, you can simplify error recovery and make your application more reliable.

Transaction ts = null;

try{

ts = new Transaction (appId);

...

...

Boolean BL = Ts.execute (SQL);

if (BL) {

BL = Ts.commit ();

}

if (!BL) {

throw new Exception ();

}

}catch (Exception e) {

if (ts!=null)

Ts.roolback ();

BL = false;

}

11. Pay attention to the efficiency of SQL execution, consider a single table record more than 10W of running effect

In Setup, when the log display level is above the warning, the SQL statement that executes longer than 300ms is output in the log warning

12. Index

Reference to "Development Management code"

third, the project development

1. Requirements:

1 demand ultimately requires developers to implement in the product, the development of unreasonable design will waste time, development technology can not achieve the design of the greatest pain: failure. Therefore, developers should pay attention to needs and needs assessment, put forward their own can think of all objections;

2 developers not only need to do a good job analysis, but also to make accurate estimates. Because the coding work quality and quantity of timely completion of the need for a variety of preparation, technical difficulties need to carry out full technical predictions, unfamiliar platform or class library to be familiar;

2. Plan: A building is difficult to estimate weight, but a brick can accurately estimate the weight. The time of a project is difficult to estimate accurately, but the project development is divided into the module function point that can no longer be divided, the estimation of each point can be more accurate estimate, from top to bottom, from bottom to top, can draw near accurate development time.

3. Design:

1) A picture wins Wan Yan, module structure and the process and so on difficult to use the text description, even if uses the text to describe also is difficult to understand, therefore in the design, should use the chart;

2 The detailed design process of thinking pain, tedious pain, but bypass these pain, coding period will face greater pain, to be happy with the attitude.

4. Code:

1 for an implementation can have a lot of solutions, spend some time and energy to choose the best solution you think can improve the overall effectiveness of work, often can also get users a better experience effect;

2 careful and rigorous work is responsible for the work, but also responsible for their own, let these become habits. Any time in the coding work, in logic, style, simple and effective and so do the best possible, not only better for the company to achieve value, at the same time more conducive to their own skills, post progress;

3 Simple is beautiful, under the premise of effective, the more simple the more precious the processing method, code writing is also, simple code easy to understand maintenance, while not easy to produce errors

4 careful to make changes, of course, not to say no changes or discourage changes, but do not make hasty, hasty code changes. There is no insight into the overall situation, and the hasty changes often do not meet the purpose of the change but bring about other problems.

5 The performance of the module is not reduced by one or several lines of code execution can be improved, performance optimization is first from the algorithm to reduce time complexity, and then start with the implementation of logic to reduce the number of execution of the Loop execution code

6 key places to print log output to the file, in the running process constantly check the log, found that any exception to check the cause and modify

5. Test:

1 for a reason, any bugs are caused by the omission of the code, using the elimination method or tracking debugging code to find the omissions;

2 to encounter their own modules related problems first check yourself, mutual prevarication will only waste time and weaken in other colleagues trust in you;

3 Station of the highly-viewed far, different perspectives have different views. Encountered more difficult to solve the problem without thinking, the conversion of ideas or the scope of the problem to put a broader, often can find solutions

4) before the function submission test or bug repair submitted verification, developers have to test their own detailed, verify the correctness of the submission. (Refer to Appendix 2--Test FAQ)

6. Other:

1) good at timely communication. In the whole process of the project, encounter other people's problems or solve their own problems, should not heap in their own hearts, to find problems in a timely manner to communicate, to seek solutions

2 good at discovering and learning the strengths of others. As a developer, we in the pursuit of close to perfection at the same time, we also need to learn to appreciate the strengths of others, discover the advantages of others, and learn from the advantages of others, into their own potential, so that we can progress faster, more comprehensive

3 good at helping others to solve problems and share knowledge experience, more conducive to their own improvement, but also to obtain the respect of others four, about testing

1. In the overall project plan, the test schedule is reasonable, the test phase of the situation should be fully anticipated, not to catch the release point and ignore the quality.

2. Be sure to clear the product package, update package, bug package submission specification. Please refer to the Development Specification manual for specific reference. Do not submit multiple bug packs during the test or submit the installation package to the tester for updates.

3. Please check the bag first, the path is correct, the file is complete, the configuration file should be submitted, the source code modification record description is perfect. Often before, the bag does not check on the direct submission to test, resulting in an error after the environment constantly restore or rebuild the new environment. CVS use is unfamiliar, submitting files repeatedly error.

4. The quality of the product needs to be strictly controlled, and the case that you admit it is a problem, please do not try and test the negotiation hope can not be prosecuted.

5. Please note that improving the quality of the bug modification, at present, to modify a bug and raise more bugs is very much the case.

6. After the modification of the bug, please verify the pass before submitting the test before submitting it, please do not submit it to the tester directly after the modification is completed, so as to prevent the bug from being repeatedly reopen.

7. In principle, it is not allowed to submit files directly to testers to debug problems and find reasons without CVS. If necessary, testers can assist in debugging, but not too often, preventing the test environment version from being difficult to control.

8. The measurement of the existence of the bug is based on the test environment and does not suggest that "my Side is good" explanation.

9. Modify the bug, please modify the complete, there may be a number of small problems submitted in a bug, bug changes in a number of small problems need to be modified.

10. The update file must be configured to publish, regardless of whether the test is not allowed to send directly to the project or directly update the client server

v. Development environment

1. Eclipse memory overflow, crash, no response, slow start

1) Establish multiple workspace

2) will be workspace in the temporary use of the project close

3 Modify Eclipse configuration file Eclipse.ini, reference Knowledge Base:

-xms512m

-xmx512m

-xx:permsize=96m

-xx:maxpermsize=96m

2. The Eclipse unified Character set is UTF-8

1 Enter the Eclipse->window->preferences->general->workspace interface, select "Other" in "Text file Encoding" and select "in the Drop-down list" UTF-8 ", and click" Apply ", click" OK "to confirm the Save

2) Modify the head of the JSP file

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "pageencoding=" Iso-8859-1 "%>

Change the character set to "UTF-8"

3 Enter the eclipse->window->preferences->web->jsp files interface, modify the "Encoding" property to "ISO 10646/unicode (UTF-8)"

4 The project has been established, right click on the project name, enter the Properties->resource interface, select "Text file Encoding" encoded as "UTF-8"

3. Open Eclipse Memory monitor and recycle plug-in

Enter the Eclipse->window->preferences->general interface, tick "show heap Status", click "Apply", click "OK" to confirm the preservation. The lower-right corner of Eclipse shows JVM memory usage.

Click on the Trash icon to manually recycle

4. Set breakpoints and debug

1) Line Breakpoint

A line breakpoint is the most common breakpoint. Just double-click in the Eclipse Java editing area to get a breakpoint and the code will stop when it runs here

2) Conditional Breakpoint

A conditional breakpoint, as its name implies, is a breakpoint with a certain condition, and the code will stop when it runs to the breakpoint only if the user's settings are met.

Click the right mouse button at the breakpoint to select the last "Breakpoint Properties"

The property interface of the breakpoint and the meaning of each option are shown below.

3) Variable Breakpoint

Breakpoints can be used not only on statements, but also on variables

The following figure is a breakpoint on a variable, the value of the variable is initialized, or variable value changes can be stopped, of course, the variable breakpoint can also add conditions, and conditional breakpoint set is the same

4) Method Breakpoint

A method breakpoint is to hit the breakpoint at the entrance of the method. Method breakpoint is unique in that it can be played in the JDK source code, because the JDK in the compilation of the debugging information removed, so the normal breakpoint can not hit the inside, but the method breakpoint is OK, you can see the method in this way the call stack

5) Type Load Breakpoint

You can see when the classes are loaded

6) Exception Breakpoint

When an exception occurs, the code stops at the occurrence of the exception, and locating the problem should be more helpful

Open Breakpoints View, click on the button to increase the exception breakpoint

5. Modify Code Font

Enter the eclipse->window->preferences->general->appearance->colors and fonts interface, select Basic->text Font, click on the right side "Edit ...", select. Click "Apply" and click "OK" to confirm the Save

6. Eclipse shortcuts, see appendix 1-eclipse shortcut keys

Six, Linux

See "Linux_ Order Detailed"

Common commands:

CD Transformation Working directory

CD/Back to root CD ... /Back to Upper directory

LS Displays the contents of the specified working directory

MV move a file to another file or move several files to another directory

Mv/data/m3/root transfer/data/m3 to the/root directory

MKDIR create the specified directory name

Mkdir/root/temp creates a temp directory under the root directory

RM Delete files and directories

RM–RF File/Folder Delete files/folders completely

RmDir Delete Empty Directory

Kill Terminate Process

Kill-9 2342 kills the process identification number PID is 2342

PS Report Process Status

Ps–ef|grep Java View Java process

Tail writes the specified file to standard output starting at the specified point

Tail–f nohup.out Real-time read log nohup.out update content

Su changes to the identity of other users

Su–user1 Switch to User user1

CP Replication

CP config.xml/data/copy config.xml files to/data/directory

Reboot reboot the server

Halt Shutdown server

Top Displays the program currently being executed in the system

Free display of system memory and swap usage

Java–version View JDK version

CHROMD 777/temp/runthread.sh gives users/temp/runthread.sh maximum permissions

Cat/dev/null > Nohup.out Empty log nohup.out file contents

DF–HL View disk space and usage

Du displays all the files in the directory and lists the file sizes

PWD View current path

Export LANG=ZH_CN Modify the environment variable lang value, solve the Linux garbled

./startup.sh Tomcat Boot

Nohup./startweblogic.sh & WebLogic Start (do not hang up the operation, prevent the cancellation after the WebLogic stop)

./startserver.sh Server1 WebSphere Startup

Vii. FAQ

1. JSP appears Getoutputstream () has already been called for this response

This error in the JSP is generally used in the JSP output stream (such as output image verification code, file download, etc.), not properly handled well caused.

JSP compiled into a servlet after the function </

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.