30 suggestions written in Java code

Source: Internet
Author: User
Tags abstract add array final garbage collection variables variable valid
30 suggestions written in Java code
(1) The first letter of the class name should be capitalized. The first letter of the field, method, and object (handle) should be lowercase. For all identifiers, all the words that are contained should be close together and capitalize the first letter of the middle word. For example:
Thisisaclassname
Thisismethodorfieldname
If a constant initialization character appears in the definition, all the letters in the static final base type identifier are capitalized. This will mark the constants that they belong to the compilation period.
Java Packages (Package) are a special case: they are all lowercase letters, even the middle word. For domain name extension names, such as Com,org,net or EDU, all should be lowercase (this is one of the differences between Java 1.1 and Java 1.2). (2) to create a class for general purposes, take "classic form" and include a definition of the following elements: Equals ()
Hashcode ()
ToString ()
Clone () (Implement cloneable)
Implement Serializable (3) For each class you create, consider placing a main () that contains the code to test that class. To use a class in a project, we do not need to delete the test code. If any form of change is made, it is easy to return to the test. The code can also be used as an example of how to use a class. (4) 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). (5) When designing a class, please put yourself in the account of the client programmer (the use of the class should be very clear). Then, put yourself in the hands of the person who manages the code and think about what kind of changes you might want to make, and how you can make them simpler.
(6) Make the class as short as possible and solve only one specific problem. Here are some suggestions for class design:
A complex switch statement: Consider the "multi-form" mechanism
A large number of methods involves the operation of a very different type: Consider using several classes to implement the
Many member variables differ significantly in their characteristics: Consider using several classes (7) to make everything "private" as--private as possible. You can make a part of a library "public" (a method, a class, a field, and so on) and never take it out. If forced to take out, it can destroy other people's existing code, so that they have to rewrite and design. If you only publish what you have to announce, you can be confident and bold in changing anything else. Privacy is a particularly important factor in a multithreaded environment-only private fields can be protected in the case of asynchronous use. (8) The "huge object syndrome". For beginners who are accustomed to sequential programming thinking and early in the field of OOP, they often prefer to write a sequential program and embed it in one or two large objects. According to programming principles, objects should express the concept of an application rather than the application itself. (9) If you have to do some awkward programming, at least you should put those code inside a class. (10) Whenever a class is found to be tightly bound to a class, it is necessary to consider whether the internal classes are used to improve coding and maintenance (see "Improving Code with internal classes" in chapter 14th 14.1.2). (11) Add comments as carefully as possible and generate your own program documentation with Javadoc annotation document syntax. (12) Avoid the use of "magic numbers", these numbers are very difficult to match the code well. If you need to modify it later, it will undoubtedly become a nightmare, because you simply do not know whether "100" means "array size" or "something completely different". So, we should create a constant, use a persuasive descriptive name for it, and take a constant identifier throughout the program. This makes the program easier to understand and easier to maintain. (13) When it comes to builders and exceptions, it is often desirable to discard any exceptions caught in the builder-if it causes the creation of that object to fail. This way, the caller does not assume that the object has been created correctly and continues blindly. (14) When the client programmer finishes using the object, if your class requires any cleanup work, consider putting the purge code in a well-defined way, using a name similar to Cleanup () to clearly indicate your purpose. In addition, you can place a Boolean (Boolean) tag within the class that indicates whether the object has been purged. In the Finalize () method of the class, make sure that the object is cleared and that a class inherited from RuntimeException (if not yet) is discarded, indicating a programming error. Before taking a scenario like this, make sure that Finalize () is able to work on its own system (you may need to call System.runfinalizersonexit (true) to ensure this behavior). (15In a specific scope, if an object must be cleared (not handled by the garbage collection mechanism), use the following method: Initialize the object, or, if successful, immediately enter a try block containing the finally clause to begin the cleanup work. (16) If you need to overwrite (cancel) finalize () in the initialization process, remember to call Super.finalize () (if object belongs to our direct superclass, this is not necessary). During the overwrite of Finalize (), the call to Super.finalize () should be the last action, not the first, to ensure that the underlying class components are still valid when they are needed. (17) When creating a set of objects of a fixed size, transfer them to an array (this should be done if you are ready to return the collection from a method). In this way, we can enjoy the benefits of array type checking at compile time. In addition, to use them, the receiver of the array may not need to "sculpt" the object into an array. (18) Use interfaces as far as possible, do not use abstract class. If something is known to be a base class, the first option should be to turn it into a interface (interface). You need to turn it into an abstract (abstract) class only if you have to use a method definition or a member variable. The interface mainly describes what the customer wants to do, while a class is committed (or allowed) to specific implementation details. (19) Within the builder, only the work that is required to set the object to the correct state. Avoid invoking other methods as much as possible, as those methods may be overwritten or canceled by others, resulting in unpredictable results during the build process (see detailed instructions in chapter 7th). (20) objects should not simply contain some data; their behavior should also be well defined. (21) When creating a new class on a ready-made class basis, select New or authoring first. This should be considered only if your own design requirements must be inherited. The entire design becomes unnecessarily complex if inheritance is used in an environment that was originally allowed to be created. (22) Using inheritance and method overlay to represent the differences between behaviors, and using fields to represent the differences between States. A very extreme example is to represent colors by inheriting from different classes, which should definitely be avoided: a "color" field should be used directly. (23) to avoid trouble with programming, make sure that each name corresponds to only one class anywhere in your classpath. Otherwise, the compiler might first find another class with the same name and report an error message. If you suspect you have encountered a classpath problem, try searching for a. class file with the same name at every point in the classpath. (24) When using event "adapters" in Java 1.1 AWT, it is particularly easy to encounter a trap. If you coverAn adapter method, while the spelling method is not particularly fastidious, the final result is to add a new method, rather than overwrite the ready-made method. However, since this is completely legal, you will not get any error prompts from the compiler or runtime system--except that the code is not working properly. (25) using reasonable design scheme to eliminate "pseudo function". That is, if you only need to create one object of the class, do not limit yourself to using the application in advance, and add a "generate one only" comment. Consider encapsulating it as an "only child" form. If you have a large number of scattered code in the main program that you use to create your own objects, consider adopting a creative solution that encapsulates some of the code. (26) Beware of "analysis paralysis". Keep in mind that you need to know the status of the project in advance, and then examine the details. Grasp the overall situation, you can quickly understand some of the unknown factors, to prevent the investigation of the details of the time into the "dead logic." (27) Beware of "premature optimization". First let it run, then consider it faster--but only if you have to do it and prove that there is indeed a performance bottleneck in some code. Unless you use a specific tool to analyze bottlenecks, it is likely that you are wasting your time. The implicit cost of performance promotion is that your code becomes difficult to understand and difficult to maintain. (28) Keep in mind that there is much more time to read code than to write code. A clear design allows for easy-to-understand procedures, but annotations, detailed explanations, and some examples are often invaluable. They are important both to yourself and to the people that come after them. If you still have doubts about this, think of the frustration you've had when trying to find useful information from an online Java document that might convince you. (29) If you think that you have done a good analysis, design or implementation, then please slightly change the thinking angle. Try inviting some outsiders--not necessarily experts, but people from other parts of the company. Ask them to look at your work in a completely fresh light and see if you can find a problem that you once turned a blind eye to. In this way, it is often possible to identify key issues in the most appropriate revision phase to avoid the loss of money and energy resulting from the issue of the product. (30) The good design can bring the biggest return. In short, for a specific problem, it usually takes a long time to find the most appropriate solution. But once the right approach is found, the work will be much easier, and no longer need to go through hours, days or months of painful struggles. Our hard work will bring the greatest rewards (or even immeasurable). And because of their devotion to a lot of painstaking efforts, and finally get an excellent design, the success of the pleasure is also exciting. Insist on resisting the temptation of a hasty completion-that often outweighs the gains (3) For each class you create, consider placing aMain (), which contains the code to test that class. To use a class in a project, we do not need to delete the test code. If any form of change is made, it is easy to return to the test. The code can also be used as an example of how to use a class. This is absolutly bad! (4) 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). (5) When designing a class, please put yourself in the account of the client programmer (the use of the class should be very clear). Then, put yourself in the hands of the person who manages the code and think about what kind of changes you might want to make, and how you can make them simpler.
(6) Make the class as short as possible and solve only one specific problem. Here are some suggestions for class design:
A complex switch statement: Consider the "multi-form" mechanism
A large number of methods involves the operation of a very different type: Consider using several classes to implement the
Many member variables differ significantly in their characteristics: Consider using several classes (7) to make everything "private" as--private as possible. You can make a part of a library "public" (a method, a class, a field, and so on) and never take it out. If forced to take out, it can destroy other people's existing code, so that they have to rewrite and design. If you only publish what you have to announce, you can be confident and bold in changing anything else. Privacy is a particularly important factor in a multithreaded environment-only private fields can be protected in the case of asynchronous use. Not necessary, pretotect or package level also fine-most case (8), I would like to express "huge object syndrome". For beginners who are accustomed to sequential programming thinking and early in the field of OOP, they often prefer to write a sequential program and embed it in one or two large objects. According to programming principles, objects should express the concept of an application rather than the application itself. (9) If you have to do some awkward programming, at least you should put those code inside a class. (10) Whenever a class is found to be tightly bound to a class, it is necessary to consider whether the internal classes are used to improve coding and maintenance (see "Improving Code with internal classes" in chapter 14th 14.1.2). (11) Add comments as carefully as possible and generate your own program documentation with Javadoc annotation document syntax. (12) Avoid the use of "magic numbers", these numbers are very difficult to match the code well. If you need to modify it later, it will undoubtedly become a nightmare, because you simply do not know whether "100" means "array size" or "something completely different". So, we should create a constant, use a persuasive descriptive name for it, and take a constant identifier throughout the program. This makes the program easier to understand and easier to maintain. (13) When it comes to builders and exceptions, it is often desirable to discard any exceptions caught in the builder-if it causes the creation of that object to fail. This way, the caller does not assume that the object has been created correctly and continues blindly. (14) When the client programmer finishes using the object, if your class requires any cleanup work, consider putting the purge code in a well-defined way, using a name similar to Cleanup () to clearly indicate your purpose. In addition, you can place a Boolean (Boolean) tag within the class that indicates whether the object has been purged. In the Finalize () method of the class, make sure that the object is cleared and that a class inherited from RuntimeException (if not yet) is discarded, indicating a programming error. In taking likeBefore such a scenario, make sure that finalize () can work on its own system (you may need to call System.runfinalizersonexit (true) to ensure this behavior). (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, or, if successful, immediately enter a try block containing the finally clause to begin the cleanup work. (16) If you need to overwrite (cancel) finalize () in the initialization process, remember to call Super.finalize () (if object belongs to our direct superclass, this is not necessary). During the overwrite of Finalize (), the call to Super.finalize () should be the last action, not the first, to ensure that the underlying class components are still valid when they are needed. (17) When creating a set of objects of a fixed size, transfer them to an array (this should be done if you are ready to return the collection from a method). In this way, we can enjoy the benefits of array type checking at compile time. In addition, to use them, the receiver of the array may not need to "sculpt" the object into an array. (18) Use interfaces as far as possible, do not use abstract class. If something is known to be a base class, the first option should be to turn it into a interface (interface). You need to turn it into an abstract (abstract) class only if you have to use a method definition or a member variable. The interface mainly describes what the customer wants to do, while a class is committed (or allowed) to specific implementation details. They are total diffrent, (19) within the builder, only the work required to set the object to the correct state. Avoid invoking other methods as much as possible, as those methods may be overwritten or canceled by others, resulting in unpredictable results during the build process (see detailed instructions in chapter 7th). (20) objects should not simply contain some data; their behavior should also be well defined. (21) When creating a new class on a ready-made class basis, select New or authoring first. This should be considered only if your own design requirements must be inherited. The entire design becomes unnecessarily complex if inheritance is used in an environment that was originally allowed to be created. (22) Using inheritance and method overlay to represent the differences between behaviors, and using fields to represent the differences between States. A very extreme example is to represent colors by inheriting from different classes, which should definitely be avoided: a "color" field should be used directly. (23) in order to avoid programming problems, please ensure that in their own classpath refers to anyPlace, each name corresponds to only one class. Otherwise, the compiler might first find another class with the same name and report an error message. If you suspect you have encountered a classpath problem, try searching for a. class file with the same name at every point in the classpath. It is particularly easy to run into a trap when using the event "adapter" in the Java 1.1 AWT when Classpath is isn't that simple (24). If you override one of the adapter methods and the spelling method is not particularly fastidious, the final result is to add a new method instead of overwriting the ready-made method. However, since this is completely legal, you will not get any error prompts from the compiler or runtime system--except that the code is not working properly. (25) using reasonable design scheme to eliminate "pseudo function". That is, if you only need to create one object of the class, do not limit yourself to using the application in advance, and add a "generate one only" comment. Consider encapsulating it as an "only child" form. If you have a large number of scattered code in the main program that you use to create your own objects, consider adopting a creative solution that encapsulates some of the code. (26) Beware of "analysis paralysis". Keep in mind that you need to know the status of the project in advance, and then examine the details. Grasp the overall situation, you can quickly understand some of the unknown factors, to prevent the investigation of the details of the time into the "dead logic." (27) Beware of "premature optimization". First let it run, then consider it faster--but only if you have to do it and prove that there is indeed a performance bottleneck in some code. Unless you use a specific tool to analyze bottlenecks, it is likely that you are wasting your time. The implicit cost of performance promotion is that your code becomes difficult to understand and difficult to maintain. But know early and design better at the is always necesary, or else
You Die (28) Keep in mind that there is much more time to read code than to write code. A clear design allows for easy-to-understand procedures, but annotations, detailed explanations, and some examples are often invaluable. They are important both to yourself and to the people that come after them. If you still have doubts about this, think of the frustration you've had when trying to find useful information from an online Java document that might convince you. (29) If you think that you have done a good analysis, design or implementation, then please slightly change the thinking angle. Try inviting some outsiders--not necessarily experts, but people from other parts of the company. Ask them to look at your work in a completely fresh light and see if you can find a problem that you once turned a blind eye to. In this way, it is often possible to identify key issues in the most appropriate revision phase to avoid the loss of money and energy resulting from the issue of the product. (30) The good design can bring the biggest return. In short, for a specific problem, it usually takes a long time to find the most appropriate solution. But once the right approach is found, the work will be much easier, and no longer need to go through hours, days or months of painful struggles. Our hard work will bring the greatest rewards (or even immeasurable). And because of their devotion to a lot of painstaking efforts, and finally get an excellent design, the success of the pleasure is also exciting. Insist on resisting the temptation of a hasty completion-that often outweighs the gains.

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.