30 tips for Java programming

  • 2020-04-01 03:22:47
  • OfStack

The first letter of the class name should be capitalized. The first letters of fields, methods, and objects (handles) should be lowercase. For all identifiers, all the words contained in them should be close together and the first letter of the middle word capitalized. Such as:

ThisIsAClassName
thisIsMethodOrFieldName

If a constant initializer character appears in the definition, all letters in the capitalized static final primitive type identifier. This marks them as compile-time constants.
Java packages are a special case: they are all lowercase, even for the middle word. For domain 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 use, take the "classic form" and include a definition of the following elements:


equals()
hashCode()
toString()
clone() ( implement Cloneable ) 
implement Serializable

For each class you create, consider putting a main() that contains the code to test that class. There is no need to remove the test code to use a class in a project. 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 classes.

Methods should be designed as brief, functional units that describe and implement a discrete part of the class interface. Ideally, the approach should be concise and to the point. If the length is large, consider some way to divide it into shorter ways. This also makes it easy to reuse code within a class (sometimes methods must be very large, but they should still do the same thing).

When designing a class, put yourself in the client programmer's shoes (the way the class is used should be very clear). Then, put yourself in the shoes of the person who manages the code (anticipate what kinds of changes are possible, and figure out how to make them easier).

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

1. A complex switch statement: consider the "polymorphic" mechanism
2. A large number of methods involve operations of vastly different types: consider implementing them separately with several classes
3. Many member variables differ greatly in their characteristics: consider using several classes

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

Beware of the huge object syndrome. For those who are new to OOP and accustomed to sequential programming thinking, it is tempting to write a sequential program and embed it in one or two large objects. According to programming principles, objects should represent the concept 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 a very tight alignment between classes, consider whether to use inner classes to improve coding and maintenance (see "improving code with inner classes" in section 14.1.2 of chapter 14).

Annotate as carefully as possible, and use javadoc annotation document syntax to generate your own program documentation.

Avoid "magic Numbers", which are hard to match with code. If you need to change it later, it's going to be a nightmare, because you don't know if "100" really means "array size" or "something completely different." Therefore, we should create a constant, give it a convincing descriptive name, and use a constant identifier throughout the program. This makes the program easier to understand and maintain.

When builders and exceptions are involved, it is common to want to discard any exceptions that were caught in the builder if it caused the creation of that object to fail. This way, the caller will not blindly proceed, assuming that the object has been created correctly.

14. When the client programmer has run out of objects and your class requires any cleanup, consider placing the cleanup code in a well-defined method with a name like cleanup() that clearly states its purpose. In addition, you can put a Boolean flag inside the class to indicate whether the object has been cleared. In the finalize() method of the class, indicate a programming error by making sure that the object has been cleared and that a class inherited from RuntimeException, if not already, has been discarded. Taking like this before, please make sure the finalize () able to work in their own systems (may need to call System. RunFinalizersOnExit (true), to ensure that this behavior).

Fifteen, in a specific scope, if an object must be cleared (not by the garbage collection mechanism), please use the following method: initialize the object; If successful, you immediately enter a try block with a finally clause and begin the cleanup.

If you need to override (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 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.

When you create a collection of fixed-size objects, transfer them to an array (especially if you want to return the collection from a method). In this way, we get the benefit of array type checking at compile time. Furthermore, the receiver of the array may not need to "sculpt" the object into the array to use them.

Use interfaces, not the abstract class. If something is known to be ready to become a base class, the first choice should be to make it an interface. Only if you have to use a method definition or a member variable do you need to make it an abstract class. The interface mainly describes what the customer wants to do, while a class focuses on (or allows for) specific implementation details.

Within the builder, only the work required to set the object to the correct state is done. Avoid calling other methods if possible, because those methods can be overwritten or canceled by others, resulting in unpredictable results during the build process (see chapter 7 for details).

Objects should not simply hold some data; Their behaviour should also be well defined.

When creating a new class on top of an existing class, select "create" or "create" first. Consider this only when your own design requirements must be inherited. If inheritance is used where new creation is allowed, the overall design becomes unnecessarily complex.

Inheritance and method overrides represent differences in behavior, and fields represent differences in state. A very extreme example is to represent colors by inheritance to different classes, which should definitely be avoided: a "color" field should be used directly.

23. To avoid programming hassles, make sure that wherever you point in your classpath, there is only one class for each name. Otherwise, the compiler might first find another class with the same name and report an error message. If you suspect you're having classpath problems, try searching for the.class file with the same name at each starting point in the classpath.

There is a particular pitfall when using event "adapters" in Java 1.1 AWT. If an adapter method is overwritten without particular care in spelling, the end result is to add a new method instead of overwriting an existing method. However, because it's perfectly legal to do so, you don't get any error messages from the compiler or the run-time system and the code just doesn't work properly.

Twenty-five, with reasonable design scheme to eliminate the "pseudo-function". That is, if you only need to create one object of the class, don't limit yourself to using the application in advance and add a "generate only one" comment. Consider encapsulating it as an "only child". If you have a lot of scattered code in the main program to create your own objects, consider adopting a creative solution that encapsulates that code.

26. Beware of "analysis paralysis". Remember, at all costs, to know the status of the project in advance, and then examine the details. As a result of grasping the overall situation, you can quickly recognize some factors that you do not know, and prevent yourself from being trapped in "dead logic" when investigating details.

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

Remember, you spend much more time reading code than writing it. Clear design leads to easy-to-understand programs, but comments, detailed explanations, and examples are often invaluable. They are important to you and to those who come after you. If you still doubt this, try to convince yourself of your frustration in trying to find useful information in online Java documents.

29. If you think you have done a good analysis, design or implementation, please change your perspective a little. Try inviting someone from outside the company. It doesn't have to be an expert, but it can be someone from another part of the company. Ask them to look at your work with a completely fresh eye and see if they can identify problems you once turned a blind eye to. In this way, it is often possible to identify critical issues at the most appropriate time for revision, avoiding the loss of money and effort that would result from fixing them after the product is released.

Good design can bring the biggest return. In short, it usually takes a long time to find the most appropriate solution to a particular problem. But once you find the right way, it's much easier to work without hours, days or months of struggle. Our hard work brings the greatest rewards (even beyond measure). And because oneself poured into a lot of painstaking care, obtain an outstanding design plan finally, the pleasure of success also makes a person enchanted. Always resist the temptation to rush through a project

 


Related articles: