Appendix C Java Programming Rules

Source: Internet
Author: User

Appendix C Java Programming Rules
This appendix contains a number of useful recommendations to help you with low-level programming and provides general guidance on code preparation: (1The 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 contained in it should be close together, and uppercase the first letter of the middle word. For example: Thisisaclassname thisismethodorfieldname If a constant initialization character appears in the definition, all letters in the static final base type identifier are capitalized. This can be used to mark the constants that they belong to the compile period. The Java package is a special case: they are all lowercase letters, even if the middle word is the same. For domain name extension names, such as Com,org,net or EDU, all should be lowercase (this is also Java1.1 and Java 1.2one of the differences). (2to create a class for general purposes, take "classic form" and include the definition of the following elements: Equals () Hashcode () toString () Clone () (implement cloneable) implemen T Serializable (3for each class that you create, consider placing a main () that contains the code for testing that class. To use a class in a project, we don't need to delete the test code. If you make any kind of change, you can easily return to the test. This code can also be used as an example of how to use a class. (4The method should be designed as a brief, functional unit that describes and implements a discontinuous class interface section. Ideally, the approach should be concise. If the length is large, consider dividing it into shorter methods in some way. This also facilitates the reuse of code within the class (sometimes the method must be very large, but they should still do the same thing). (5when designing a class, put yourself in the mind of the client programmer (the way the class is used should be very explicit). Then put yourself in the person who manages the code and think about what kind of changes you're expected to make, and how you can make them easier. (6) makes the class as short as possible, and only solves a specific problem. Here are some suggestions for class design: A complex switch statement: Consider a large number of ways to use the "multi-shape" mechanism involves a very different type of operation: Consider using several classes to implement a number of member variables separately in the characteristics of a very big difference: Consider the use of several classes (7) make everything as "private" as possiblePrivate. To make a part of a library "public" (a method, a class, or a field, etc.), you can never take it out. If you force it out, you can break the existing code of others so that they have to rewrite and design it. If you only publish what you have to announce, you can be confident and bold to change anything else. In a multithreaded environment, privacy is a particularly important factor-only private fields can be protected in the case of non-synchronous use. (8I would like to tiglate the "huge object syndrome". For beginners who are accustomed to sequential programming thinking and start with the field of OOP, they often prefer to write a sequential program and embed it in one or two large objects. According to the principle of programming, an object should represent the concept of an application, not the application itself. (9If you have to do some unsightly programming, you should at least put those code inside a class. (10any time you find that the combination of classes and classes is very close, you need to consider whether to use an internal class to improve coding and maintenance (see Chapter 14th).1.2"Improve code with internal classes" in the section). (11add comments as carefully as possible, and generate your own program documentation using the Javadoc annotation document syntax. (12Avoid using magic numbers, which are hard to match with your code. If you need to modify it later, it will undoubtedly become a nightmare, because there is no knowing "100"What does it mean," array size "or" something completely different "? Therefore, we should create a constant and use a persuasive descriptive name for it, with constant identifiers throughout the program. This makes the program easier to understand and easier to maintain. (13when it comes to builders and exceptions, you typically want to discard any exceptions caught in the builder--if it causes the creation of that object to fail. In this way, the caller does not assume that the object was created correctly and thus blindly continues. (14When the client programmer finishes using the object, if your class requires any cleanup work, consider putting the cleanup code in a well-defined method, using a name like Cleanup () to clearly indicate your purpose. In addition, a Boolean (Boolean) token can be placed inside the class to indicate whether the object has been purged. In the Finalize () method of the class, make sure that the object has been purged and discarded from the678RuntimeException inherits a class (if not yet) to indicate a programming error. Before you take a scenario like this, make sure that Finalize () is able to work in your own system (you may need to call System.runfinalizersonexit (true), thus ensuring this behavior). (15in a specific scope, if an object must be purged (not handled by the garbage collection mechanism), use the following method: Initialize the object, or, if successful, immediately enter a try block with a finally clause to begin the cleanup work. (16If you need to overwrite (cancel) finalize () during initialization, remember to call Super.finalize () (This is not necessary if object belongs to our direct superclass). In the process of covering the Finalize (), theSuperthe call to finalize () should belong to the last action, not the first action, which ensures that they remain in effect when the underlying class components are needed. (17When you create a set of objects that are fixed in size, transfer them to an array (this should be done if you are going to return the collection from a method). In this way, we can enjoy the benefits of array type checking at compile time. Also, to use them, the receiver of the array may not need to "sculpt" the object into the array. (18) Try to use interfaces, do not useAbstractclass. If something is known to be a base class, the first choice should be to turn it into a interface (interface). Only if you have to use a method definition or member variable, you need to turn it into an abstract (abstract) class. The interface mainly describes what the customer wants to do, while a class is committed (or allowed) to specific implementation details. (19inside the builder, only the work that is required to set the object to the correct state. Avoid invoking 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 description in chapter 7th). (20objects should not simply accommodate some data, their behavior should also be well defined. (21stwhen creating a new class based on an off-the-shelf class, first select New or authoring. This should only be considered when the design requirements must be inherited. The entire design becomes unnecessarily complex if inheritance is used in a scenario that would otherwise have been allowed to be created. (22use inheritance and method overrides to represent differences between behaviors, and fields to represent differences between states. A very extreme example is the representation of colors by inheriting different classes, which should definitely be avoided: a "color" field should be used directly. (23to avoid trouble with programming, make sure that each name corresponds to only one class at any place where the classpath refers. 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 of the same name at each start of the classpath. (24) in Java 1.1when using the event "adapter" in AWT, it is particularly easy to hit a trap. If an adapter method is overridden and the spelling method is not particularly fastidious, the final result is to add a new method instead of overwriting the off-the-shelf method. However, since this is perfectly legal, no error hints are obtained from the compiler or the runtime system--only the work of the code becomes unhealthy. (25) Eliminate "pseudo-function" with reasonable design scheme. That is, if you only need to create an object of the class, don't limit your use of the application in advance, and add a "generate only one" comment. Consider encapsulating it in the form of an "only son". If you have a lot of messy code in the main program that you use to create your own objects, consider adopting a creative approach to encapsulating some of the code. (26) Beware of "analysis paralysis". Keep in mind, however, that you should be aware of the overall project situation in advance and examine the details. Grasp the overall situation, you can quickly understand some of their unknown factors, to prevent the investigation of the details of the time into the "logic of Death." (27) Beware of "premature optimization". First let it run, and then consider it faster--but only if you have to do it, and it's proven that there is a performance bottleneck in some code, it should be optimized. Unless you use specialized tools to analyze bottlenecks, it is likely that you are wasting your time. The hidden cost of performance improvement is that your code becomes difficult to understand and difficult to maintain. (28keep in mind that reading code is much more time than writing code. Clear-minded design provides easy-to-understand procedures, but annotations, detailed explanations, and some examples are often invaluable. They are very important to you, and to those who are later. If you're still skeptical, think about the frustration of trying to find useful information from an online Java document that might persuade you. (29If you think you have done a good analysis, design or implementation, then please change the angle of thinking a little. 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 at the most appropriate stage of the revision, avoiding the loss of money and energy due to the problem being solved after the product is released. (30a good design can bring the greatest return. In short, for a particular problem, it usually takes a long time to find the most appropriate solution. But once the right approach is found, it is easier to work later, without having to go through the painful struggles of hours, days, or months. Our hard work results in maximum returns (even immeasurable). And thanks to a lot of work, and finally get an excellent design, the thrill of success is also exciting. Insist on resisting the temptation of a hasty completion--that often outweighs the loss. 

Appendix C Java Programming Rules

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.