From my second day, I started to learn Basic. I tried to unify my code writing rules, and I have been now, I also think that my code is written is very standard (may be in some differences with the textbook). Now, Java I have to treat it with C-like writing rules, but before doing, I will go to find it, I can find some helpful experience. First: "Programming style of C language"
Title C Language Programming Style Selection Self - programming Style C Language Programming Style from Shaohui BLOG Keyword C
Chapter 1: The indent format Tab is 8 characters, so indentation is also 8 characters. There are many weird style, they define the indentation format as 4 characters (set to 2 characters!), This It is unconfiring that the PI is defined as 3. The reason is that the indentation is to clearly define the beginning and end of a block. Especially when you have stayed in front of your computer for more than 20 hours, you It will find a large indentation format makes your understanding of the program. Now, some people say that the use of 8 characters is used to make the code very close to the right side, watch the program very much on the 10-character width terminal screen. Uncomfortable. Answer is, but your program has more than 3 indentation, you should modify your program. In short, the indentation of 8 characters makes the program easy to read, there is an additional benefit, that is, it can Give you a warning when you get the program nested layers. At this time, you should modify your program. Chapter II: Location of the big symbol Di-program programming style problem is the processing of braces Different from the size of the moisture, there is almost no reason to choose one without choosing another style, but there is a recommended style, it is the classic book of kernighan and Ritchie, it will start Brackets are placed in the end of the line, and the end of the brace is placed in a row, as shown below: if (x is true) {we do y} However, there is a special case: Name function: Started parentheses It is the first line in the next line, as follows: int function (int x) {body of function} All non-orthodox people will not be difficult this inconsistency, but all the thinking people understand: (first) K & R is right If K & R is wrong, see Article 1 (: -)) ... In addition, the function is also special, not necessarily consistent. Need to pay attention to the end of the brackets The line is empty, except that it follows the continued symbol of the same statement. As "while" in the Do-While loop, or "else" in the IF statement. As follows: do {body of do-loop} while Condition); and if (x == y) {..} else f (x> y) {...} else {.... Reasons: K & R. In addition, it is noted that the placement method of this braces reduces the number of spaces, but there is no readability. So, when the screen size is limited, you can have more blank lines. To write some comments. Chapter 3: Naming System C is a simple language, then naming should also be concise. Unlike module-2 and pASCAL languages, C programmers do not use such as thisvariableisatemporarycounter. Named mode. The programmer of a C language will be named "TMP", which is easy to write, and it is not so difficult to understand. However, when the name of the mixed type has to appear, the descriptive name is a global variable. It is necessary. Calling a function called "foo" global function is very annoyed. Global variables (only when you have to use it), just like global functions, you need a descriptive naming method If you have a function to calculate the number of active users, you should be named - "Count_Active_Users ()" - Or additional similar form, you should not name "CNTUSR ()". There is a kind of hungarian Named mode, it is written to the variable name of the type of function, which is a manifestation of the brain - the compiler knows this type and then check it, and this will only confuse programmers. Know why Micro $ OFT produces so many "bug" procedures !!. The naming of local variables should be short and delicate. If you have a random integer loop counter, it may have "i", if there is no possibility to make it If you can be misunderstood, write it "loop_counter" is low efficiency. Similarly, "TMP"
Can be a function variable for any temporary value. Chapter 4: The function function should be short and charming, and it only makes only one thing. It should only cover one to two screens (80 * 24 screen), and only one Things and do it well. (This is not a unix style, the translator's note). The maximum length and function of a function is inversely compared. So if you have written simple but length Long function, and you have done a lot of small things to different situations, and write a longer function. However, if you want to write a very complex function, and you have estimated that if the average Read this function, he may not know what this function is saying. At this time, use a helpful function with a descriptive name. Another need to consider the number of local variables. They should not exceed 5-10, Otherwise you may be wrong. Recise this function, divide them into smaller functions. People's brains can often be easily remembering 7 different things, more than this quantity will cause confusion. You know you are very smart, But you may still want to understand what you did before 2 weeks. Chapter 5: Comment comments are a good thing, but too much comments are dangerous, don't try to explain your code is how to explain how Ok: You should write the code better, not a lot of time to explain those bad code. Usually, your comment is to explain what your code is done, not how to do. And, to try Avoid inclusion in a function body: If this function is indeed, you need some comments in it, you should go back to the fourth chapter. You can write some short comments to indicate or warn those you. It is considered to be particularly smart (or extremely ugly) part, but you have to avoid too much. Instead, write the comment before the function, tell others what is doing something, and why you have to do this. Second: " Code Writing Specification (Java) "
Code Writing Specification (Java) article published: System Posted: 2003-02-28 Readings: A Java code to write out a few days before 437! Code writing specification 1, for the purpose of the code, the primary requirement is that it must be correct and can run according to the real thoughts of the programmer; the second request is that the code must be clear, so that other programmers can easily understand the code. practical work. In the field of software engineering, the origin of the source program is marked with maintenanceability, readability, an important part of the software project. And there is currently no coding style documentation, so that many times, the programmer does not have a common standard, which can be followed, the coding style is different, the program is maintenanceability, and readability is also very poor. By establishing code writing specification, forming development team coding conventions, improving program reliability, readability, modification, maintainability, inheritability, and consistency, guarantee the quality of program code, inheriting software development results, full Use resources to make the developers' work results can be shared. Based on the existing coding style of the industry, this paper describes a JBuilder-based project style, strive for a unified programming style, from the overall coding style, code file style, function writing style, variable style, annotation style, etc. Several aspects are elaborated. (These norms are not necessarily abolished, but must make the program have good readability) Second, the overall coding style 1, indent indentation suggestions in 4 spaces. It is recommended to set the block IDent of the Editor page in Tools / Editor Options to 4, Tab Size is 8. Pretreatment statements, global data, title, additional instructions, function description, label, etc. are written. The "{", "}" pair alignment of the statement block, and is aligned with the previous row, the statement of the statement block classes is recommended for each "{", "}" separately, which is easy to match. The default mode in JBuilder is the beginning "{" is not a single line, it is recommended to change into the above format (set in the Project / Default Project Properties Setting Code STYle Select Braces to NEXT LINE). 2, space in principle variables, classes, constant data, and functions in its type, and the appropriate space between the modified name is aligned. Keyword principles, such as: if (...), etc.. The space for the operator is as follows: "::", "->", "[", "]", " ", "-", "~", "!", " ", "-" (Specific Negative Negative Number), "&" and other operators are not vacuum (where the single operator is connected to the operand), other operators (including most budget operators and The three-mean operator "?:" The two sides plus a space, and it can be aligned in the case when the function is defined, but it can be not available when the function is implemented. "," The operator is only in it. Grid, you can also be empty or more spaces. No matter whether there is parentheses, the annotation of the comment after the statement is applied to the statement and the statement is as aligned. Personally think that this item can be followed according to the personal habitual decision. 3 The relationship between the relationship between the alignment is aligned, and alignment includes various parts of the type, modification, name, parameters.
The length of each row should not exceed too much screen. If necessary, the wrap is appropriate, when the wrap is as possible, "," or operator, it is best to take the operator after the wrap, and the following lines are in the first line of this statement. Injunction, but the statement is still subject to the indentation of the first line, that is, the next line is "{" should be aligned with the first line. The variable definition is preferably aligned by adding spaces, and the same type of variable is preferably placed together. As shown in the following example: int value; int result; intlength; Object CurrenTry; individual thinks this item can be followed or not in accordance with personal habits. 4. There is no rule-free space, such as 10 consecutive spaces. Two rows between the sections of the program file structure, if it is not necessary, it can only be empty, each function is generally empty. Since each function must have a function explanation, it is usually only empty or not empty. However, there should be at least a row for the case where there is no function description. For your own functions, it is recommended to share "// ------". The function internal data and the code should be at least one line, and the code should be spaced in the code. It is recommended to have a variable declaration in the code in the code. At least four "P" in the class, there is also a space between the data and the function therein. 5. Comment Notes is the specific embodiment of software readability. The program annotation amount generally accounts for 20% of the program encoding, and the software engineering requirements are not less than 20%. Program comments cannot be used in abstract languages, similar to "processing", "loop" computer abstract language, to accurately express the procedure's processing instructions. For example: "Calculate Net Demand", "calculate the processing of the first step", etc. ". Avoid using comments per line programs, you can add a period of annotation in front of a program to have a clear processing logic. Note is essential, but should not be too much, do not write annotations for write comments. The following is four essential notes: A. Title, additional instructions. B. Description of functions, class, etc. For almost every function, there should be an appropriate description, usually before the function implementation, before the function implementation part, the content is mainly the function, purpose, algorithm, etc. of the function, the parameter description , Return value description, etc., there must be some instructions such as special hardware and software requirements if necessary. Common functions, publications of public classes must be made by annotation, and design ideas, of course, choose the appropriate naming format to help you explain more clearly. C. There must be some instructions in the code that does not clearly or inlet. D. and a small amount of other comments, such as the annotation of custom variables, code writing time, etc. Note There is two kinds of bidders and line bets, which refers to: "/ ** /" and "//" recommendation to a block annotation, D line notes, B, and C depend on the situation, but should be unified, At least Class B annotation in one unit should be unified. Specific pairs of different documents, structural annotations will be described in detail later. 6, the code length is recommended for each function to control the length of 53 rows as much as possible, and the code exceeding 53 rows should be re-considered to split it into two or more functions. The function split rules should not undermine the original algorithm, and the part of the split should be reused. For repetitive code to be used in multiple modules or forms, it can be independently become a function with public nature, placed in a common module. 7, page wide page width should be set to 80 characters. Sourcecodes generally do not exceed this width and cause the unable to display, but this setting can also be flexible. In any case, the long statement should be folded after a comma or a operator. One statement fold It should be more compared to 2 characters more than the original statement. 8, in general integrated programming environment, each screen can only display a program that does not exceed 50 rows, so this function is about 5-6 screen display, in a certain There are 8 screens to be 8 screens in some environments.
In this way, whether it is a reader or a modification process, it will be difficult. It is therefore recommended to extract the block of completing the comparison independent function, and become a function separately. Take the block that completes the same or similar functions, independently is a child function. It can be found that the more the functions of the upper layer are, the more sub-function, the more the product is completed, the more the base is completed. This is a sign of a good program. This way, we can easily control the logic of the entire program in a lower function, and focus on the implementation of a certain aspect in the underlying function. Third, all Java (*. Java) files must comply with the following style rules:. File generation For specification Java derived classes, try to generate file formats with JBuilder's Object Gallery tools to avoid manual headers File / implementation file. Package / Import Package Directions Before the IMPORT row, the standard package name in the Import is previously arranged in the locally, and is arranged in alphabetical order. If the IMPORT line contains different subdirectory in the same package, you should use * to process. Package hotlava.net.stats; import java.io. *; import java.util.observable; import hotlava.util.Application; here java.io. * is used instead of InputStream and OutputStream. The header note of the file header is mainly indicative of some information of the file, which is an overall instructions for the program, enhances the readability and maintainability of the program. The file header is generally after the Package / Imports statement, the class description. Require at least the file name, creator, create time, and content description. In the code generated by JBuilder's Object Gallery tool, we must add a comment in the class, and we also add some comments. It should be intended to be constant as possible: / ** * title: Determine the mouse location * Description: Determine the mouse Which job field is in the job number * @copyright: Copyright (c) 2002 * @company: hit * @Author: rivershan * @version: 1.0 * @Time: 2002.10.30 * /. Class Next is the class Comments are generally used to interpret classes. / ** * a class representing a set of packet and byte counters * it is observable to allow it to be watched, but only * reports changes when the current set is completion * / Next is a class definition, which contains different lines EXTENDS and IMPLEMENTS PUBLIC CLASS CLONEABLE .CLASERVABLE IMPLEments Cloneable .Class Fields Next is the member variable of the class: / ** * packet counter * / protected int [] packets; member variables for publicococ (javadoc). Member variables defined by Proceted, Private and Package If the name meaning is clear, you can not comment. The access method is next to the access to the class variable. It is just simple to get values to assign values to the class variable, you can simply write on one line.
(Individual thinks as much as possible) / ** * get the counters * @return an array containing The statistical data. This array ha modified by the caller. * / Public int [] getpackets () {Return CopyArray (Packets, Offset); PUBLIC INT [] getBytes () {return copyArray (bytes, offset);} public int [] getpackets () {return packets;} public void setpackets (int [] packets) {this.packets = Packets;} Other methods do not write on a line. The constructor is next to construct a function, which should be written in an incremental manner (such as: the parameter is written behind). Access Type ("Public", "Private", etc.) and any "static", "firm" or "synchronized" should be written in one line, and the methods and parameters can be written separately, which makes the method and parameters easier to read.
PubliccounterSet (int size) {this.size = size;}. Clone method If this class can be cloned, then the next step is Clone method: publicobject clone () {Try {counter = (counterset) Super.clone () ; obj.packets = (int []) packets.clone (); obj.size = size; return obj;} catch (CloneNotSupportedException e) {throw new InternalError ( "Unexpected CloneNotSUpportedException:" e.getMessage ());} }. Method: / ** * set the packet counter * (Such as When Restoring from a database) * / protected finalvoid setArray (int [] R1, int [] R2, int [] R3, INT [] R4) THROWS ILLEGALARGUMENTEXCEPTION {/// EnSure the arrays are of equal size //iff (r1.length! = r2.length || r1.length! = r3.length || r1.length! = r4. Length) Throw New IllegalargumentException ("Arrays Must Be of the Same Size"); System.Arraycopy (R1, 0, R3, 0, R1.Length); System.ArrayCopy (R2, 0, R4, 0, R1.LENGTH) }.}. In any case, every class should define the TOSTRING method: publicString toString () {string retval = "counterset:"; for (int i = 0 i Function Comment System Automatically generated functions, such as mouse action response functions, etc., don't have much annotation and interpretation; As follows: / *** Function name: * Editor: * Reference: * Features: * Enter parameters: * Output parameters: * 备: * / I want to follow the above format. V. Symbol style. General requirements For the definition of various symbols, there is a common point, which is to use the abbreviation of English words or English words, do not use simple but meaningless strings, do not use Arabia Digital, don't use the first letters of Chinese Pinyin. Such name is not advocated: Value1, Value2, Value3, Value4 .... For example: file (file), code (number), DATA (data), PagePoint, Faxcode, Address, Bank, Bank, .... variable name a. Variable name Frost convention variable type prefix example integer int intCountbyte byt bytMoveshort sht shtResultlong lng lngTotalfloat flt fltAveragedouble dbl dblTolerangceboolean bln blnIsoverChar chr chrInput Array arr arrData variable names generally have a certain expression meaning, the first letter of the variable name in every word of every Updably (remove the first word) b. Descriptive variable name and process name: the main body of the variable name or process name uses case in size and as much as possible to describe its purpose, and the process name should be started with verb as: initNameArray , CloseDialog agreed object name: prefix convention object name: Object type prefix Button btnCanvas cvsCheckBox chkImage imgLabel lblList lstChoice chcDialog dlgEvent evtFrame frmMenu menuPanel pnlTextArea txaTextField txf named the Package Package names should be lowercase words are from a composition. The name of the name of the Class of Class must consist of one or several words or abbreviations that can be started with the meaning of the meaning of the meaning of the meaning of the class, which makes the name of this class can be easier to understand. The name of the name variable of the Class variable must be started with a lowercase letter. The latter words begin with uppercase letters. For a member variable of the class, add the prefix M_ of the Member (member) when naming its identifier. For example, an identifier is m_dwflag, it represents a variable that is a type of two-word, which represents a flag. The name of the name static final variable should be capitalized and point out the full meaning. The name of the name of the name of the parameter must be consistent with the naming specification of the variable. . Array named arrays should always be named in the following ways: byte [] buffer; not: byte buffer [];. The parameters of the method use meaningful parameters, if possible, use the field to assign the value Name: setcounter (int size) {this.size = size;}. Mysterious number is first to say what is mysterious. We often use some quantities in the program, it has a specific meaning. For example, now we write a salary statistics, 50 employees, we will use 50 this number in the program to make a variety of calculations. Here, 50 is "mysterious number". Why call it mystery? Because other programmers see 50 this number in the program, I don't know its meaning, I can only guess. "Mysterious number" in the program will reduce the readability of the program and should try to avoid it. Avoiding the method to define the mysterious number as a constant. Note that this constant should be able to express the meaning of the number and should be all override to distinguish from the identifier corresponding to the variable. For example, the number above 50, we can define a constant named NumofemPloyees instead. This way, other programmers can be easily understood when they read the program. The first article is to speak C, but it should also be applicable to Java, but he can't accept it except for the fourth and fifth chapters. I thought I was a heterogeneous. It turns out that my code is written so unprofessional (-_- b). Then look at the second article "The code writing specification (Java)", I only saw the part about indentation, I have already taken the palm. It's just the same as the rules I insist. Huang Tian did not bear someone. I have always written VB and C a norm to write specification with Java code.