30 Java coding experience sharing

  • 2020-06-07 04:26:50
  • OfStack

Good coding habits are essential to be a good Java programmer. Let's take a look at 30 Suggestions for code writing.

(1) Class names should be capitalized. Fields, methods, and objects (handles) should begin with a lowercase letter. For all identifiers, all the words contained in it should be next to 1 and capitalized with the first letter of the middle word. Such as:


If a constant initializer character appears in the definition, all letters in the uppercase static final primitive type identifier are capitalized. This marks them as constants at compile time.

The Java package is a special case: they are all lowercase, even for middle words. For domain extensions such as com, org, net, or edu, all should be in lower case (this is the difference between Java 1.1 and Java 1.2).

(2) When creating a class for general use, take the "classic form" and include definitions for the following elements:

clone() ( implement Cloneable )  
implement Serializable

(3) For each class you create, consider placing an main() containing the code to test that class. To use a class in a project, we don't need to delete the test code. If any changes have been made, you can easily return the tests. 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 can be used to describe and implement a discontinuous part of the class interface. Ideally, the approach should be concise and to the point. If the length is large, consider somehow splitting it into shorter methods. This also facilitates reuse of code within a class (sometimes methods must be very large, but they should still only do the same thing).

(5) When designing a class, please put yourself in the client programmer's shoes (the usage of the class should be very clear). Then, put yourself in the person's shoes to manage the code (anticipate the possible forms of changes and think about ways to make them easier).

(6) Make the class as short and concise as possible and solve only one specific problem. Here are 1 Suggestions for class design:

A complex switching statement: consider using a "multiform" mechanism
A large number of methods involve operations of very different types: consider implementing them separately in several classes
Many member variables differ greatly in their characteristics: consider using several classes

(7) Make everything as private as possible. You can make a part of the library "public" (a method, class, field, etc.), and you can never take it out. If you force it out, you may break someone else's existing code, forcing them to rewrite and design it. If you publish only what you have to publish, you can confidently change everything else. In a multithreaded environment, privacy is a particularly important factor. Only the private field can be protected if it is used asynchronously.

Beware of the giant object syndrome. For a novice who is used to sequential programming and is new to OOP, it is common to write a sequential program and embed it in one or two large objects. According to programming principles, objects should represent the concepts of the application, not the application itself.

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

(10) Any time you find that classes are tightly bound to each other, you need to consider whether to use inner classes to improve coding and maintenance (see "Improving Code with Inner Classes," section 14.1.2, chapter 14).

(11) Annotate as carefully as possible, and generate your own program documents with javadoc annotation document syntax.

(12) Avoid using "magic Numbers", which are difficult to match with code. If you need to modify it later, it will be a nightmare because you never know whether "100" means "array size" or "something completely different". Therefore, we should create a constant, give it a convincing descriptive name, and use 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 usually want to discard any exceptions caught in the builder if it caused the creation of that object to fail. In this way, the caller will not blindly continue with the object as if it had been created correctly.

(14) If your class requires any cleanup when the client programmer has run out of objects, consider putting the cleanup code in a well-defined method with a name like cleanup() to make it clear what you're doing. In addition, you can place an boolean (Boolean) tag within the class to indicate whether the object has been cleared. In the class's finalize() method, make sure that the object is cleared and that the class inherited from RuntimeException (if not already) is discarded to indicate a programming error. Before adopting a scenario like this, make sure that finalize() is able to work on its own system (you may need to call ES61en.runFinalizersOnExit (true) to ensure this 1 behavior).

(15) Within a specific scope, if an object must be cleared (not handled by the garbage collection mechanism), initialize the object; If successful, you immediately enter an try block containing an finally clause and begin the cleanup.

(16) If you need to override (cancel) finalize() during initialization, remember to call super.finalize () (not necessary if Object belongs to our direct superclass). During the override of finalize(), the call to super.finalize () should belong to 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 collection of objects of fixed size, transfer them to an array (especially if you intend to return the collection from a method). In this way, we can enjoy the benefit of array type checking at compile time. In addition, recipients of arrays may not need to "sculpt" objects into arrays to use them.

(18) Use interfaces instead of the abstract class. If something is known to be ready to become a base class, then the first option is to turn it into an interface (interface). You only need to turn it into an abstract (abstract) class if you have to use method definitions or member variables. The interface basically describes what the customer wants to do, while a class focuses on (or allows for) the specific implementation details.

(19) Within the builder, only the work needed to set the object to the correct state is done. Avoid calling other methods whenever possible, as those methods may be overridden or cancelled by others, resulting in unpredictable results during the build process (see Chapter 7 for details).

(20) Objects should not simply hold 1 bit of data; Their behaviour should also be well defined.

(21) When creating a new class based on the existing class, first select "New" or "Create". This should only be considered if your design requirements must be inherited. When inheritance is used where it would otherwise be allowed to be created, the whole design becomes unnecessarily complex.

(22) Inheritance and method overrides are used to represent the differences between behaviors, while fields are used to represent the differences between states. A very extreme example is representing colors by inheriting from different classes, which should definitely be avoided: you should use a "color" field directly.

(23) To avoid programming problems, make sure that there is only one class for each name anywhere you point to on your classpath. Otherwise, the compiler might first find another class with the same name and report an error message. If you suspect you have a classpath problem, try searching for the.class file with 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 you overwrite an adapter method with no particular spelling, you end up adding a new method instead of overwriting the existing one. However, because it is perfectly legal to do so, you do not get any error messages from the compiler or the runtime system, but the code does not work properly.

(25) Eliminate "fake function" with reasonable design scheme. That is, if you only need to create one object of your class, don't limit your use of the application ahead of time and add a "generate only one" comment. Consider encapsulating it as an "only child". If you have a large amount of scattered code in the main program to create your own objects, consider adopting a creative approach to encapsulating some of the code.

(26) Watch out for "analysis paralysis." Remember, at any rate, to know the project in advance before you go into the details. Because of grasping the overall situation, we can quickly understand some unknown factors, so as to prevent us from falling into the "dead logic" when we examine the details.

(27) Beware of premature optimization. Get it up and running first, then think about making it faster, but only if you have to and it turns out there is a performance bottleneck in some part of the code. Unless you use specialized tools to analyze bottlenecks, you're probably wasting your time. The hidden cost of improved performance is that your code becomes difficult to understand and difficult to maintain.

(28) Remember that you spend a lot more time reading code than writing it. A clear design leads to an easy-to-understand program, but notes, detailed explanations, and a few examples are often invaluable. They are of great importance to you and to those who come after you. If in doubt, imagine your frustration trying to extract useful information from the online Java documentation.

(29) If you think you have done a good analysis, design or implementation, please change your thinking Angle slightly. Try inviting some outsiders, some of whom may not necessarily be experts, but may come from other parts of the company. Ask them to look at your work in a completely fresh light and see if they can spot a problem you haven't seen for a while. In this way, it is often possible to identify key issues at the most suitable stage of modification and avoid the loss of money and effort caused by solving problems after the product is released.

Good design brings the greatest rewards. In short, it often takes a long time to find the most appropriate solution to a particular problem. But once you find the right way, your work will be much easier and you won't have to struggle for hours, days or months. Our hard work will bring the greatest rewards (even incalculable). And because he poured a lot of effort, finally get an excellent design, the pleasure of success is also exciting. It often pays to resist the temptation to rush things.

Related articles: