JVA basics: 30 suggestions for writing JAVA code

Source: Internet
Author: User
JVA basics: 30 suggestions for writing JAVA code-general Linux technology-Linux programming and kernel information. For details, see below. (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 identifiers, all the words in them should be placed together, and the first letter of the intermediate 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 one of the differences between Java 1.1 and 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 the code used to test that class. 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 methods in some way. This also facilitates the reuse of code in the class (sometimes, the methods must be very large, but they should still 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's look at the form of changes that may be made to the person who manages the code (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. A certain part of the database can be "public" (a method, class, or a field, etc.), and it will never be taken out. If you forcibly extract the code, it may damage the existing Code of others, so that they have to rewrite and design it. If you only publish what you must publish, You can boldly change anything else. In a multi-threaded environment, privacy is a particularly important factor-only private fields can be protected in non-synchronous use.

(8) Please refer to "huge object syndrome ". For new users who are used to sequential programming and are initially involved in the OOP field, they often prefer to write an ordered execution program first and then embed it into one or two huge objects. According to programming principles, objects should be expressed as the concept of applications rather than 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, to 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, it will undoubtedly become a nightmare, because you do not know whether "100" refers to "array size" or "other totally different things ". Therefore, we should create a constant, use a persuasive descriptive name for it, and use constant identifiers throughout the program. 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 causes the creation of that object to fail. In this way, the caller will not blindly continue to think that the object has been correctly created.

(14) after a client programmer uses up an object, if your class requires any cleanup work, consider placing the cleanup code in a well-defined method that is similar to cleanup () such a name clearly indicates its purpose. In addition, you can place a boolean mark in the class to indicate whether the object has been cleared. In the finalize () method of the class, 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 scheme like this, make sure that finalize () can work in your own System (you 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 yes, then, immediately enter a try block containing the finally clause to start clearing.

(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 to finalize () should belong to the last action, rather than the first action, which ensures that they are still valid when basic components are required.

(17) when creating a set of fixed-size objects, transmit them to an array (this operation is more appropriate if you are going to return this set from a method ). In this way, we can enjoy the benefits of checking the type of arrays during compilation. 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 be a basic class, the first choice should be to convert it into an interface ). You need to change a method definition or a member variable to an abstract class. The interface mainly describes what the customer wants to do, 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 other methods whenever possible, because those methods may be overwritten or canceled by others, resulting in unpredictable results during the build process (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 ". This issue should be considered only when the design requirements must be inherited. If inheritance is used in the scenario where new users are allowed, the entire design becomes unnecessary.

(22) Use inheritance and method overwrite to represent the differences between actions, while use fields to represent the differences between States. An extremely extreme example is to represent colors by inheriting different classes, which should be avoided: A "color" field should be used directly.

(23) to avoid programming troubles, make sure that each name corresponds to only one class at any place indicated by your class path. Otherwise, the compiler may first find another class with the same name and report an error message. If you suspect that you have encountered a class path problem, try to 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 adapter method is overwritten and the spelling method is not particular, the final result is to add a new method instead of overwriting the existing method. However, this is completely legal, so it does not get any error prompts from the compiler or runtime system-except that 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, do not restrict your use of the application in advance, and add a "generate only one" comment. Consider encapsulating it into an "Only Child" form. If there is a large amount of scattered code in the main program to create your own objects, consider adopting 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 examine the details. By grasping the global conditions, you can quickly identify unknown factors to prevent details from falling into the "dead logic.

(27) be alert to "premature optimization ". First let it run, and then consider getting faster-But optimization should be performed only when you have to do so and it has been confirmed that there is indeed a performance bottleneck in some code. Unless you use a dedicated tool to analyze the bottleneck, you may be wasting your time. The hidden cost of performance improvement is that your code becomes hard to understand and difficult to maintain.

(28) Remember that reading Code takes much more time than writing code. A program with clear thinking can be easily understood, but comments, detailed explanations, and examples are often invaluable. They are important to both yourself and those who are later. If you still have doubts about this, think about the setbacks you encounter when trying to find useful information from the online Java documentation. This may convince 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 to take a fresh look at your work and see if you can find out what you once turned a blind eye on. In this way, we can often find some key problems in the most suitable period to avoid the financial and energy losses caused by solving the problems after the product is released.

(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 in the future will be much easier, and there will be no need 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 put a lot of effort into it and finally got an outstanding design scheme, 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

(3) For each class you create, consider placing a main (), which contains the code used to test that class. 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.

This is absolutly bad!

(4) the method should be designed into a brief functional unit to describe and implement a non-sequential class Interface part. Ideally, the method should be concise. If the length is large, you can divide it into several shorter methods in some way. This also facilitates the reuse of code in the class (in some cases, the method must be very large, but they should 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's look at the form of changes that may be made to the person who manages the code (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. A certain part of the database can be "public" (a method, class, or a field, etc.), and it will never be taken out. If the code is forcibly extracted, the existing Code of others may be broken, so that they have to rewrite and design. If you only publish what you must publish, You can boldly change anything else. In a multi-threaded environment, privacy is a particularly important factor-only private fields can be protected in non-synchronous use.

Not necessary, pretotect or package level also fine in most case

(8) Please refer to "huge object syndrome ". For some new users who are used to sequential programming and are initially involved in the OOP field, they often prefer to write a program for sequential execution and then embed it into one or two huge objects. According to programming principles, objects should be expressed as the concept of applications rather than the application itself.

(9) If you have to do some unsightly programming, at least put those codes in the internal part of 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, to improve coding and maintenance (see "improve code generation using 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, it will undoubtedly become a nightmare, because you do not know whether "100" refers to "array size" or "its totally different things ". Therefore, we should create a constant, use a persuasive descriptive name for it, and use constant identifiers throughout the program. 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 causes the creation of that object to fail. In this way, the caller will not blindly continue to think that the object has been correctly created.

(14) after a client programmer uses up an object, if your class requires any cleanup work, consider placing the cleanup code in a well-defined method that is similar to cleanup () such a name clearly indicates its purpose. In addition, you can place a boolean mark in the class to indicate whether the object has been cleared. In the finalize () method of the class, 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 scheme like this, make sure that finalize () can work in your own System (you 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 yes, then, enter a try block containing finally clauses to start clearing.

(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 to finalize () should belong to the last action, instead of the first action, which ensures that they are still valid when basic components are required.

(17) when creating a set of fixed-size objects, transmit them to an array (more so if you want to return this set from a method ). In this way, we can enjoy the benefits of checking the type of arrays during compilation. In addition, to use them, the receiver of the array may not need to "shape" the image into the array.

(18) Try to use interfaces instead of abstract classes. If you know that something is ready to be a basic class, the first choice should be to convert it into an interface ). You need to change a method definition or a member variable to an abstract class. The interface mainly describes what the customer wants to do, 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 other methods as much as possible, because those methods may be overwritten or canceled by others, resulting in unpredictable results during the build process (see the detailed descriptions 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 ". This issue should be considered only when your design requirements must be inherited. If inheritance is used in the scenario where new users are allowed, the entire design becomes unnecessary.

(22) Use inheritance and method overwrite to represent the differences between actions, while use fields to represent the differences between States. An extremely extreme example is to represent colors by inheriting different classes, which should be avoided: A "color" field should be used directly.

(23) to avoid programming troubles, make sure that each name corresponds to only one class at any place indicated by your class path. Otherwise, the compiler may first find another class with the same name and report error message. If you suspect that you have encountered a class path problem, try to search for the. class file with the same name at every starting point of the class path.

Classpath is not that simple

(24) when using the event "adapter" in Java 1.1 AWT, it is particularly prone to a trap. If an adapter method is overwritten and the spelling method is not particular, the final result is to add a new method instead of overwriting the existing method. However, this is completely legal, so it does not get any error prompts from the compiler or runtime system-except that the Code work becomes abnormal.

(25) Eliminate "pseudo functions" with reasonable design schemes ". That is to say, if you only need to create a pair of classes, do not restrict your use of the application in advance, and add a "generate only one of them" comment. Consider encapsulating it into an "Only Child" form. If there is a large amount of scattered code in the main program and it is used to create your own objects, consider adopting 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 examine the details. By grasping the global conditions, you can quickly identify unknown factors to prevent details from falling into the "dead logic.

(27) be alert to "premature optimization ". First let it run, and then consider getting faster-But optimization should be performed only when you have to do so and it has been confirmed that there is indeed a performance bottleneck in some code. Unless you use a dedicated tool to analyze the bottleneck, you may be wasting your time. The hidden cost of performance improvement is that your code becomes hard to understand and difficult to maintain.

But know early and design better at first is always necesary, or else
You die

(28) Remember that reading Code takes much more time than writing code. A well-defined design can produce easy-to-understand programs, but comments, detailed explanations, and Examples often have immeasurable price values. They are important to both yourself and those who are later. If you are still skeptical about this, think about the setbacks you encounter when trying to find useful information from the online Java documentation. This may convince you.

(29) if you think you have performed a good analysis, design, or implementation, please change your thinking angle slightly. Try inviting outsiders-not necessarily experts, but from other departments of the company. Ask them to take a fresh look at your work and see if you can find out what you were once familiar. In this way, we can often find some key problems in the most suitable period to avoid the financial and energy losses caused by solving the problems after the product is released.

(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 in the future will be much easier, and there will be no need to go through several hours, days, or months of hard work. Our hard work will bring the greatest return (or even immeasurable ). In addition, the pleasure of success is also exciting because I have poured a lot of blood into my heart and finally got an outstanding design plan. Stick to the temptation to resist the completion of grass and grass-that is often not worth the candle.
Related Article

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.