30 Suggestions for Java programming _java

Source: Internet
Author: User
Tags garbage collection lowercase

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:

Copy Code code as follows:
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).

Second, to create a class for general purposes, take "classic form" and include a definition of the following elements:

Copy Code code as follows:

Equals ()
Hashcode ()
ToString ()
Clone () (Implement cloneable)
Implement Serializable

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.

The method should be designed as a concise, functional unit, using it to describe and implement a discontinuous class interface part. 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).

When designing a class, please put yourself in the account of the client programmer (the class usage 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.

Make the class as short as possible and solve only one particular problem. Here are some suggestions for class design:

1. A complex switch statement: Consider the "multi-shape" mechanism
2. A large number of methods involve the operation of a very different type: Consider using several classes to implement each
3. Many member variables differ significantly in their characteristics: Consider the use of several classes

Let everything be "private" –private as much 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.

Eight, 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.

Nine, if you have to do some of the less elegant programming, at least the code should be placed inside a class.

Whenever a class is found to be tightly coupled 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).

Annotate as carefully as possible and generate your own program documentation with Javadoc annotation document syntax.

12, avoid the use of "magic number", these numbers are difficult to work well with the code. 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).

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 you create a set of objects of a fixed 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. In addition, to use them, the receiver of the array may not need to "sculpt" the object into an array.

18, try to use interfaces, 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 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 behaviour 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, with inheritance and method coverage to represent the differences between the behavior, and the field to represent the difference 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 point to any place, 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.

24, when using the event "adapter" in the Java 1.1 AWT, it is particularly easy to encounter a trap. 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 – but the code is not working properly.

25, with a reasonable design scheme to eliminate the "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, vigilance "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, you should optimize it. 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 the time spent reading the code is much more than the time it has 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 can be 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.