Java programming rules

Source: Internet
Author: User

This appendix contains a large number of useful suggestions to help you design low-level programs and provide general instructions for coding:
(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 the identifiers should be placed together and capitalized.

The first letter of the intermediate word. 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. For domain name extension names, such as COM, org, net, or Edu

Must 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 Generation.

. 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 consider

Some way to divide it into several shorter methods. This method also facilitates repeated use of the code in the class (sometimes the methods 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 consider it for the person who manages the code (pre-

Determine which forms of modifications may be made, and 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 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 a program for sequential execution and then embed it into one or two

A huge object. 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 discover that classes are closely integrated with each other, you need to consider whether internal classes are used to improve coding and maintenance (see "in-use" in section 14.1.2 of Chapter 14th.

Class improvement Code ").
(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 don't know what "100" means.

"Array size" or "other totally different things ". Therefore, we should create a constant, use a persuasive descriptive name for it, and use constants throughout the program.

Identifier. 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 does not

Will assume that the object has been correctly created, and thus blindly continue.
(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 ().

The sample name clearly indicates your 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, please

Determines 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 successful, immediately enter

Try block of 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

In the process of overwriting finalize (), the call to super. Finalize () should belong to the last action, instead of the first action. This ensures that when basic class components are needed

They are still valid.
(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

To the benefit of checking the type of the array 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 (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.

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

Unpredictable results are generated 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

If inheritance is used in the new application, 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 is absolute

Avoid: Use a "color" field 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 messages. 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

Is to add a new method, rather than overwrite the existing method. However, this is completely legal, so no error message is returned from the compiler or runtime system-

The Code becomes abnormal.
(25) Eliminate "pseudo functions" with a reasonable design scheme ". 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 "only generate

"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

And 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 get to know your unknown one.

To prevent details from falling into the "dead logic.
(27) be cautious about "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 indeed a performance bottle in some code

When the neck, should be optimized. 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 is difficult to maintain.
(28) Remember that reading Code takes much more time than writing code. A program with clear ideas can be easily understood. However, annotations, detailed explanations, and Examples often have

Measurable value. They are important to both yourself and those who are later. If you still have doubts about this, try to find useful information from the online Java documentation.

The setbacks you encounter may persuade you.
(29) if you think that you have performed a good analysis, design, or implementation, change your mind slightly. Try inviting some outsiders-not necessarily experts,

Persons 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. This method is often the most suitable

Find out some key problems in the modification phase, and avoid the financial and energy losses caused by solving the problem 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. But once it is found correct

In the future, the work will be much easier, and there is no need to go through several hours, days, or months of pain. Our hard work will bring the greatest return (or even immeasurable ). While

The pleasure of success is also exciting because you have invested a lot of effort to finally get an outstanding design solution. Stick to the temptation to resist the completion of Caocao-doing so is often not worth the candle

.
(31) You can find a large number of programming reference resources on the web, including a large number of news groups, discussion groups, mailing lists, and so on. Here are a lot of useful links:
Http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/mm-WebBiblio.html

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.