30 suggestions for writing Java code (reproduced)
(1) The first letter of the class name should be capitalized. The first letter of the field, method, and object (handle) should be in lowercase. For all labels
Identifier, and all the words in it should be placed together, and the first letter of the middle word should be capitalized. For example:
Thisisaclassname
Thisismethodorfieldname
If a constant initialization character appears in the definition, all the letters in the static final basic type identifier are capitalized.
. In this way, they are constants of the compilation period.
A Java package is a special case where all these are lowercase letters, even the middle words.
. All domain name extension names, such as COM, org, net, or Edu, should be in lower case (this is also Java 1.1 and
One of the differences between Java 1.2 ).
(2) When creating a class for the general purpose, take the "classic form" and include the definition of the following elements:
Equals ()
Hashcode ()
Tostring ()
Clone () (implement cloneable)
Implement serializable
(3) For each class you create, consider placing a main (), which contains
Code. To use a class in a project, we do not need to delete the test code. If any form of modification is made,
You can easily return to the test. These codes can also be used as an example of how to use classes.
(4) the method should be designed into a brief functional unit to describe and implement a discontinuous class interface section.
Ideally, the method should be concise. If the length is large, you can divide it into several shorter ones in some way.
Methods. This method also facilitates repeated use of the code in the class (in some cases, the methods must be very large, but they should still be
Only do the same thing ).
(5) When designing a class, consider it for the client programmer. (the usage of the class should be very clear.
). Then, let us look at it for the person who manages the Code (which forms of modifications are expected,
Think about how to make them easier ).
(6) Make the class as short and concise as possible, and only solve a specific problem. The following are some suggestions for class design:
■ A complex switch statement: consider adopting the "multi-form" Mechanism
■ A large number of methods involve very different types of operations: Consider using several classes to implement them separately
■ Many member variables have major differences in features: Consider using several classes
(7) Make everything "private" -- private as much as possible. Make a part of the database "public" (a method,
Class, a field, and so on. If it is forcibly extracted, it may damage the existing
Code, so that they have to rewrite and design. If you only publish what you must publish, you can change it with confidence.
Anything else. In a multi-threaded environment, privacy is a particularly important factor-only private fields can be stored in
Protection for non-synchronous use.
(8) Please refer to "huge object syndrome ". For some beginners who are used to sequential programming and are initially involved in the OOP field
I like to write a program for sequential execution first, and then embed it into one or two huge objects. Based on programming principles,
The object represents the concept of an application, not the application itself.
(9) If you have to do some unsightly programming, at least put the code inside a class.
(10) at any time, as long as you find that classes are closely integrated with each other, you need to consider whether internal classes are used.
Improve coding and maintenance (see "improve code with internal classes" in section 14.1.2 of Chapter 14th ").
(11) add comments as detailed as possible and generate your own program documents using javadoc annotation Document Syntax.
(12) Avoid using "magic numbers", which are difficult to work with code. If you need to modify it later, no doubt
It will become a nightmare, because I don't know whether "100" refers to "array size" or "other totally different things.
". Therefore, we should create a constant and use a persuasive descriptive name for it, and in the entire program
Constant identifiers are used. This makes the program easier to understand and maintain.
(13) when it comes to the builder and exceptions, you usually want to discard any exceptions captured in the Builder -- if it
The creation of the object fails. In this way, the caller will not assume that the object has been correctly created.
And blindly continue.
(14) when the client programmer uses up the object, if your class requires any cleanup, consider clearing the code
Put it in a well-defined method and use a name like cleanup () to clearly indicate its purpose.
In addition, you can place a Boolean mark in the class to indicate whether the object has been cleared. In the F
In the inalize () method, make sure that the object has been cleared and a class inherited from runtimeexception has been discarded.
(If not) to indicate a programming error. Before taking a solution like this, please confirm Fina
Lize () can work in its own system (it may need to call system. runfinalizersonexit (true ),
To ensure that this row is ).
(15) In a specific scope, if an object must be cleared (not handled by the garbage collection mechanism), use
The following method: Initialize the object. If the initialization succeeds, immediately enter a try block containing the finally clause to start clearing.
Work.
(16) If You Need to overwrite (cancel) Finalize () during initialization, remember to call Super. Finalize ()(
This is not necessary if the object belongs to our direct superclass ). In the process of overwriting finalize (),
The call of super. Finalize () should belong to the last action, instead of the first action. This ensures that
They are still valid when you want basic components.
(17) when creating a set of fixed-size objects, transmit them to an array (if you are going to return from a method
This set should be operated in this way ). In this way, we can enjoy the array type check during compilation.
Benefits. In addition, to use them, the receiver of the array may not need to "shape" the object into the array.
(18) Try to use interfaces instead of abstract classes. If you know that something is ready to become a basic class
The first choice should be to convert it into an interface ). Only when the method definition or
The member variable must be converted into an abstract class. The interface mainly describes
Hope to do something, and a class is committed to (or allowed) specific implementation details.
(19) within the builder, perform only the work required to set the object to the correct state. Avoid calling it whenever possible
This method, because those methods may be overwritten or canceled by others, resulting in unpredictable knots during the build process.
Result (see the detailed description in Chapter 7th ).
(20) objects should not simply contain some data; their behaviors should also be well defined.
(21) when creating a new class based on the existing class, select "new" or "CREATE" first ". Only have their own design requirements
This issue should be considered only when inheritance is required. If inheritance is used in the scenario where new data is allowed, the entire
It becomes unnecessary.
(22) Use inheritance and method overwrite to represent the differences between actions, while use fields to represent the differences between States. A very extreme
In this example, colors are represented by inheritance of different classes, which should be avoided: A "face" should be used directly.
Color "field.
(23) to avoid programming problems, make sure that each name corresponds to only
A class. Otherwise, the compiler may first find another class with the same name and report an error message. If you suspect that you have met
If the class path is incorrect, search for the. Class file with the same name at every starting point of the class path.
(24) when using the event "adapter" in Java 1.1 AWT, it is particularly prone to a trap. If an appropriate
The spelling method is not very particular. The final result is to add a new method instead of overwrite it.
Ready-to-use method. However, since this is completely legal, it does not obtain any information from the compiler or runtime system.
Error prompt-only the code becomes abnormal.
(25) Eliminate "pseudo functions" with reasonable design schemes ". That is to say, if you only need to create an object of the class
You must restrict your use of the application in advance and add a "generate only one" comment. Consider encapsulating it
An "Only Child" form. If there is a large amount of scattered code in the main program to create your own objects, consider
Adopt a creative solution to encapsulate some code.
(26) be alert to "analysis paralysis ". Remember to know the status of the entire project in advance in any case, and then check it again.
. By grasping the global conditions, you can quickly identify unknown factors to prevent details from falling in.
In "dead logic.
(27) be alert to "premature optimization ". First let it run, and then consider getting faster -- but only when you have to do so
And it is confirmed that there is a performance bottleneck in a part of the code before optimization. Unless used exclusively
Tool analysis bottleneck, otherwise it is likely to be a waste of time. The hidden cost of performance improvement is your own.
The Code becomes difficult to understand and maintain.
(28) Remember that reading Code takes much more time than writing code. Easy to understand with clear ideas
But annotations, detailed explanations, and some examples often have immeasurable value. For yourself,
For later people, they are very important. If you still have doubts about this, please think about your attempt to connect
Find out the setbacks encountered when useful information is in the Java document, which may persuade you.
(29) if you think that you have performed a good analysis, design, or implementation, change your mind slightly.
Try inviting outsiders-not necessarily experts, but from other departments of the company. Ask them
Check your work with a fresh eye and see if you can find out what you once looked. Take this approach
To find some key problems in the most suitable modification phase, and avoid solving the problems after the product is released.
Financial and energy losses.
(30) good design can bring the greatest return. In short, a specific problem usually takes a long time.
To find the most appropriate solution. However, once the correct method is found, the work will be much easier in the future.
You no longer have to go through several hours, days, or months of hard work. Our hard work will bring the greatest return.
(Or even immeasurable ). In addition, because I have devoted a lot of effort, I finally got an outstanding design solution
The pleasure of success is also exciting. Stick to the temptation to resist the completion of Caocao-doing so is often not worth the candle
Website recommendations:
Http://www.javaresearch.org★★★★★
Http://www.matrix.org.cn★★★★★
Http://www.blogjava.net★★★★★
Http://forum.hibernate.org.cn Java sight Forum★★★★★
Http://www.open-open.com/★★★★★
Http://www.itpub.net/
Http://www.javarss.com.cn/
Http://www.chinaitlab.com/www/school/codesearch/index.html source code
Http://spaces.msn.com/atian25 (BUPT)