Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Java Code Writing Specification

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the Java code writing specification example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

I. purpose

For code, the first requirement is that it must be correct and can run according to the real thinking of the programmer; the second requirement is that the code must be clear and easy to understand so that other programmers can easily understand what the code is actually doing. In the field of software engineering, the unified style of source programs marks maintainability and readability, and is an important part of software projects. At present, there is no written coding style document, so that in many cases, programmers do not have a common standard to follow, different coding styles, poor program maintainability and poor readability. By establishing the coding specification, forming the coding agreement of the development team, improving the reliability, readability, modification, maintainability, inheritance and consistency of the program, we can ensure the quality of the program code and inherit the results of software development. make full use of resources, so that the results of work among developers can be shared.

On the basis of referring to the existing coding style in the industry, this paper describes a project style based on JBuilder, strives for a unified programming style, and expounds it from several aspects, such as overall coding style, code file style, function writing style, variable style, annotation style and so on. (these specifications do not have to be followed absolutely, but the program must be made readable.)

Second, the overall coding style

1. Indent

Indentation is recommended in 4 spaces. It is recommended that you set the Block ident of the Editor page in Tools/Editor Options to 4 and Tab Size to 8. Preprocessing statements, global data, titles, additional instructions, function descriptions, labels, etc., are all written in the top box. The "{" and "}" pairs of the statement block are aligned and aligned with the previous line, and the sentence indentation of the statement block class suggests that each "{", "}" has a separate line for easy matching. The default method in JBuilder is that the initial "{" is not a separate line, and it is recommended to change it to the above format (select Braces as Next line in setting Code Style in Project/Default Project Properties).

2. Spaces

In principle, variables, classes, constant data, and functions are properly spaced between their types, decorated names and aligned as appropriate. Keyword principle over a space, such as: if (...) and so on. The spaces of operators are as follows: ","-> "," [","] "," + + ","-"," ~ ","! "," + ","-"(refers to the sign)," & "(reference) and other operators without spaces on both sides (where the unitary operator refers to the side connected to the Operand). Other operators (including most binocular and ternary operators "?:" add a space on both sides, and can be aligned with multiple spaces or no spaces as appropriate when defining a function, but not when the function is implemented. " The operator is only followed by a space, and may not be empty or multiple spaces when alignment is required. With or without parentheses, apply appropriate spaces to the comments after the statement line and align them as much as possible. Personally, I think this item can be followed according to personal habits.

3. Alignment

In principle, closely related lines should be aligned, including type, modifier, name, parameter and other parts of alignment. The length of each line should not exceed the screen too much, if necessary, the appropriate line change, as far as possible in the "," or operator, it is best to start with the operator after the line break, and the following lines are indented by the first line of the statement, but the statement is still subject to the indentation of the first line, that is, if the next behavior "{" should be aligned with the first line.

Variable definitions are best aligned by adding spaces, and variables of the same type are best put together. As shown in the following example:

Int Value

Int Result

Int Length

Object currentEntry

Personally, I think this item can be followed according to personal habits.

4. Blank line

There must be no irregular blank lines, such as ten consecutive blank lines. Program file structure between the various parts of the blank two lines, if not necessary can only be a blank line, each function implementation is generally blank two lines, because each function also needs to have a function description comment, so usually only need a blank line or not empty, but for no function description should be at least another blank line. It is recommended to add "/ / -" to separate the functions written by yourself. There should be at least one line of space between the internal data of the function and the code, and there should be a blank line where appropriate in the code. It is recommended to leave a line before the variable declaration in the code. There should be at least one blank line between the four "p" in the class, and between the data and the function in the class.

5. Notes

Comments are the concrete embodiment of software readability. The amount of program comments generally accounts for 20% of the amount of program coding, and the requirement of software engineering is not less than 20%. Program comments can not be used in abstract language, such as "processing", "loop" and other computer abstract language, it is necessary to accurately express the processing instructions of the program. For example, "calculate the net demand", "calculate the processing hours of the first process" and so on. Avoid using comments for each line of program, you can add a comment in front of a section of the program, with clear processing logic.

Comments are essential, but they should not be too much. Do not passively write comments for the sake of writing notes. Here are four necessary comments:

a. Title, additional description.

b. Description of functions, classes, etc. There should be an appropriate description for almost every function, usually before the implementation of the function, or in the case of no part of the function implementation, before the function prototype, which mainly focuses on the function, purpose, algorithm, parameter description, return value description, etc., as well as some special software and hardware requirements when necessary. The declaration of common functions and common classes must be annotated to explain their usage and design ideas, of course, choosing the appropriate naming format can help you explain things more clearly.

c. There must be some explanation where the code is not clear or not portable.

d. And a small number of other comments, such as comments for custom variables, code writing time, etc.

There are two kinds of comments: block comments and line comments, respectively: "/ * /" and "/ /" it is recommended to use block comments for A, line comments for D, and line comments for B and C as appropriate, but they should be unified, and the form of class B comments should be unified in at least one unit. Specific notes on different files and structures will be explained in detail later.

6. Code length

For each function, it is recommended to control the length of its code to about 53 lines as much as possible, and code with more than 53 lines should reconsider splitting it into two or more functions. The function splitting rule should be based on the original algorithm, and the split part should be reused. For repetitive code that is used in multiple modules or forms, you can independently become a function with a common nature and place it in a common module.

7. Page width

The page width should be set to 80 characters. The source code generally does not exceed this width and cannot be fully displayed, but this setting can also be flexibly adjusted. In any case, overly long statements should be wrapped after a comma or an operator. After a statement is wrapped, it should be indented by 2 more characters than the original statement.

8. Number of rows

In a general integrated programming environment, each screen can only display no more than 50 lines of programs, so this function needs about 5-6 screens, and in some environments it takes about 8 screens to display. As a result, it will be difficult to read or modify the program. Therefore, it is suggested that the program blocks that complete more independent functions should be extracted and become a separate function. The program blocks that perform the same or similar functions are extracted and separated into a subfunction. It can be found that the higher the function is, the simpler it is to call several subfunctions, and the more specific the function is, the more specific the work is. This is a sign of good procedure. In this way, we can easily control the logic of the whole program in the upper functions and focus on the implementation of certain functions in the functions at the bottom.

Third, code file style

All Java (* .java) files must follow the following style rules:

. File generation

For canonical JAVA-derived classes, try to use JBuilder's Object Gallery tool to generate file formats, avoiding handmade header files / implementation files.

. Package/import

The package line should precede the import line, and the standard package name in import should precede the local package name and be arranged alphabetically. If the import line contains different subdirectories in the same package, it should be handled with *.

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.

. File header comment

The file header comment is mainly to show some information of the file, is the overall description of the program, and can enhance the readability and maintainability of the program. The file header comment is usually placed after the package/imports statement and before the Class description. At least the file name, creator, creation time and content description are required. Comments are automatically added to the code generated by JBuilder's Object Gallery tool in classes, project files, and so on. We also need to add some comments. The format should be as follows:

/ * *

* Title: determine the mouse position class

* Description: determine which job bar the mouse is currently in and return the job number

* @ Copyright: Copyright (c) 2002

* @ Company: HIT

* @ author: rivershan

* @ version: 1.0

* @ time: 2002.10.30

, /

. Class

The next step is the comments of the class, which is generally used to explain the class.

/ * *

* 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 complete

, /

Next is the class definition, which contains the extends and implements on different lines

Public class CounterSet

Extends Observable

Implements Cloneable

.Class Fields

Then there are the member variables of the class:

/ * *

* Packet counters

, /

Protected int [] packets

The member variables of public must generate a document (JavaDoc). Member variables defined by proceted, private, and package can be uncommented if the name is clear.

. Access method

Then there is the method of accessing the class variable. It is simply used to assign the variable of the class to get the value, it can be simply written on one line. (personally, I think we should try to write in branches.)

/ * *

* Get the counters

* @ return an array containing the statistical data. This array has been

* freshly allocated and can be 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 should not be written on one line.

. Constructor function

Then there is the constructor, which should be written incrementally (for example, if there are many parameters written at the end).

Access type ("public", "private", etc.) And any "static", "final" or "synchronized" should be on one line, and the methods and parameters should be written on a separate line, which makes the methods and parameters more readable.

Public

CounterSet (int size)

{

This.size = size

}

. Cloning method

If this class can be cloned, the next step is the clone method:

Public

Object clone ()

{

Try

{

CounterSet obj = (CounterSet) super.clone ()

Obj.packets = (int []) packets.clone ()

Obj.size = size

Return obj

}

Catch (CloneNotSupportedException e)

{

Throw new InternalError ("Unexpected CloneNotSUpportedException:"

+ e.getMessage ()

}

}

. Class method

Let's start writing the method of the class:

/ * *

* Set the packet counters

* (such as when restoring from a database)

, /

Protected final

Void setArray (int [] R1, int [] R2, int [] R3, int [] R4)

Throws IllegalArgumentException

{

/ /

/ / Ensure the arrays are of equal size

/ /

If (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)

}

. ToString method

In any case, every class should define a toString method:

Public

String toString ()

{

String retval = "CounterSet:"

For (int I = 0; I < data.length (); iTunes +)

{

Retval + = data.bytes.toString ()

Retval + = data.packets.toString ()

}

Return retval

}

. Main method

If the main (String []) method is defined, it should be written at the bottom of the class.

Fourth, function writing style

. Naming of functions

In general, the naming of a function is based on the principle that it can express the meaning of the action. It is usually started with a verb, followed by a noun indicating the object of action, and the first letter of each word should be capitalized. In addition, there are some general rules for naming functions. If you take a number, start with Get, and then follow the name of the object you want to take; set the number, start with Set, and then follow the name of the object you want to set; and the function in the object that acts in response to the message can be named On, followed by the name of the corresponding message; the function for active action can be named Do, and then the name of the corresponding action. There are many similar rules, which require programmers to read more excellent programs and gradually accumulate experience in order to make good function naming.

. Function comment

Functions automatically generated by the system, such as mouse action response functions, do not need too many comments and explanations.

For a self-written function, if it is a key function of the system, the information of the function must be marked at the top of the function implementation. The format is as follows:

/ * *

* function name:

* author:

* reference materials:

* function:

* enter parameters:

* output parameters:

* remarks:

, /

I hope to follow the above format as much as possible.

Fifth, symbol style

. General requirements

The definitions of all kinds of symbols have one thing in common, that is, we should use meaningful English words or abbreviations of English words, do not use simple but meaningless strings, and avoid Arabic numerals as much as possible. do not use the initials of Chinese pinyin. A name like this is not recommended: Value1,Value2,Value3,Value4.

For example:

File (file), code (number), data (data), pagepoint (page pointer), faxcode (fax number), address (address), bank (bank of deposit),...

. Variable name

a. Convention for variable name prefix

Example of variable type prefix

Integer int intCount

Byte byt bytMove

Short sht shtResult

Long lng lngTotal

Float flt fltAverage

Double dbl dblTolerangce

Boolean bln blnIsover

Char chr chrInput

Array arr arrData

The variable name usually has a certain meaning, and the first letter of each word in the variable name should be capitalized (except the first word).

b. Descriptive variable name and procedure name:

The body of a variable name or procedure name uses a mixed case format and describes its purpose as completely as possible, and the procedure name should start with verbs such as: InitNameArray, CloseDialog

. Conventions for object names:

Prefix convention for object names:

Object type prefix

Button btn

Canvas CVS

CheckBox chk

Image img

Label lbl

List lst

Choice chc

Dialog dlg

Event evt

Frame frm

Menu menu

Panel pnl

TextArea txa

TextField txf

. Naming of Package

The name of Package should be made up of a lowercase word.

. Naming of Class

The name of a Class must consist of one or more words or abbreviations that begin with uppercase letters that express the meaning of the class and all other letters are lowercase, so that the name of the Class can be understood more easily.

. Naming of Class variables

Variable names must begin with a lowercase letter. The following words begin with capital letters. For a member variable of a class, when naming its identifier, add the prefix m _ for member (member). For example, if an identifier is m_dwFlag, the variable it represents is a member variable of type double word, which represents a flag.

. Naming of Static Final variables

The names of Static Final variables should be capitalized and indicate the full meaning.

. Naming of parameters

The name of the parameter must be consistent with the naming convention of the variable.

. Naming of the array

Arrays should always be named in the following way:

Byte [] buffer

Instead of:

Byte buffer []

. Parameters of the method

Use meaningful parameter naming and, if possible, the same name as the field to assign:

SetCounter (int size)

{

This.size = size

}

. A mysterious number

First of all, let's talk about what is a mysterious number. We often use some quantity in the program, and it has a specific meaning. For example, now we write a salary statistics program, the company has 50 employees, we will use the number 50 to do all kinds of calculations in the program. Here, 50 is the "mysterious number". Why do you call it mystery? Because other programmers see the number 50 in the program, do not know its meaning, can only rely on guessing.

The appearance of "mysterious numbers" in the program will reduce the readability of the program and should be avoided as much as possible. The way to avoid it is to define the mysterious number as a constant. Note that the naming of this constant should express the meaning of the number and should be all capitalized to distinguish it from the identifier corresponding to the variable. For example, the number 50 above can be defined as a constant called NUMOFEMPLOYEES instead. In this way, other programmers can easily understand when they read the program.

Thank you for reading this article carefully. I hope the article "sample Analysis of Java Code Writing Specification" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report