30 Lessons from writing Java code

Source: Internet
Author: User

To be a good Java programmer, it is essential to have a good code-writing habit. Let's take a look at 30 suggestions for code writing.

(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 contained in it should be close together, and uppercase the first letter of the middle word. For example:

Thisisaclassnamethisismethodorfieldname

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 one of the differences between Java 1.1 and Java 1.2).

(2) When creating 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 that you create, consider placing a main () that contains the code used to test 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.

(4) The method should be designed as a brief, functional unit, which describes and implements a discontinuous class interface part. 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).

(5) When designing a class, put yourself in the mind of the client programmer (the method of using the class should be very clear). 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) Make the class as short and concise as possible, and solve only one particular problem. Here are some suggestions for class design:

    • A complex switch statement: Consider using the "multi-shape" mechanism
    • A large number of methods involve operations of a very different type: Consider using several classes to implement each
    • Many member variables differ greatly in their characteristics: Consider using several classes

(7) to make everything as "private" as possible –private. 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.

(8) I would like to tiglate "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.

(9) If you have to do some inappropriate programming, you should at least put those code inside a class.

(10) Whenever it is found that the combination of classes and classes is very close, it is necessary to consider the use of the internal class, thereby improving the coding and maintenance work (see Chapter 14th, "Using internal classes to improve code 14.1.2").

(11) Annotate as carefully as possible and generate your own program documentation using the Javadoc annotation document syntax.

(12) Avoid the use of "magic numbers", these numbers are difficult to match with the code well. If you need to modify it later, it will undoubtedly become a nightmare, because it is not known whether "100″" means "array size" or "other completely different things". 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.

(13) When 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.

(14) When 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 similar to 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 that a class inherited from RuntimeException has been discarded (if not already) 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) 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 with a finally clause to begin the cleanup work.

(16) If 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 overwriting a finalize (), the call to Super.finalize () should be the last action, not the first action, which ensures that the underlying class components are still valid when they are needed.

(17) when creating a set of objects of 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. 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 use abstract class. 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.

(19) Inside 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).

(20) objects should not simply accommodate some data; their behavior should also be well defined.

(21) When creating a new class based on an off-the-shelf class, first select New or author. 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.

(22) Inheritance and method overrides are used to represent differences between behaviors, and fields are used 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.

(23) to avoid trouble with programming, make sure that each name corresponds to only one class at any place where your 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) When using the event "adapter" in Java 1.1 AWT, it is particularly easy to encounter 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 code's work 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 have proven that there is a performance bottleneck in some of the code that 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.

(28) Keep 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.

(29) If you think you have done a good analysis, design or implementation, then please change the angle of thinking a little bit. 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.

(30) 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.

30 Lessons from writing Java code

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.