Java basics-methods required to design a Java class
Source: Internet
Author: User
Java basics-methods required to design a Java class-general Linux technology-Linux programming and kernel information. For details, refer to the following section. (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 them should be placed together, and the first letter of the intermediate word should be capitalized. 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. All domain name extension names, such as com, org, net, or edu, should 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 code. 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 divide it into several shorter methods in some way. This also facilitates the reuse of code in the class (sometimes, the methods must be very large, but they should still 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 look at the form of changes that may be made to the person who manages the code (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" as much as possible "?? Private. 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.
(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 find that classes are closely integrated with each other, you need to consider whether to use internal classes to improve coding and maintenance.
(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 whether "100" refers to "array size" or "other totally different things ". Therefore, we should create a constant, use a persuasive descriptive name for it, and use constant identifiers throughout the program. This makes the program easier to understand and maintain.
(13) when it comes to the builder and exceptions, do 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 will not blindly continue to think that the object has been correctly created.
(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 () such a name clearly indicates its 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, make sure 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 yes, then, immediately enter a try block containing the 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 the process of overwriting finalize. the call to finalize () should belong to the last action, rather than the first action, which ensures that they are still valid when basic components are required.
(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 the benefits of checking the type of arrays 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 ). 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, and a 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 whenever 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 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 inheritance is used in the scenario where new users are allowed, 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 should be avoided: A "color" field should be used 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 an error message. 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 to add a new method instead of overwriting the existing method. However, this is completely legal, so no error prompts will be returned from the compiler or runtime system ?? But 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 comment "only generate one. 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 solution to 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 identify unknown factors to prevent the details from falling into the "dead logic.
(27) be cautious about "premature optimization ". First let it run, and then consider becoming faster ?? However, optimization should be performed only when you have to do so and it is confirmed that a performance bottleneck exists in some code. 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 difficult to maintain.
(28) Remember that reading Code takes much more time than writing code. A program with clear thinking can be easily understood, but comments, detailed explanations, and examples are often invaluable. They are important to both yourself and those who are later. If you still have doubts about this, think about the setbacks you encounter when trying to find useful information from the online Java documentation. This may convince 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, but people 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. In this way, we can often find some key problems in the most suitable period to avoid the financial and energy losses caused by solving the problems 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. However, once the correct method is found, the work in the future will be much easier, and there will be no need to go through several hours, days, or months of hard work. Our hard work will bring the greatest return (or even immeasurable ).
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.