Java Programming Guidelines
Abstract: "Java Programming Ideology" 2nd Edition "Appendix C J A V) Criteria / (US) Ecr (Eckel, B); Waiting, Machinery Press, 2002.9
Copyright belongs to the original author and the original publisher.
The recommendations provided by this appendix can help you low-order programming and help you write code.
Of course, these are just a policy rather than hard rules. You should regard them as a source of inspiration. Remember, in some cases you need to do or even break the rules.
design
1. Elegant needs to pay the price. From short-term benefits, an elegant solution to a problem seems to have more time. However, when it is finally able to perform correctly and easily in the new case, you don't need to spend several hours, even when you have a day or monthly, you will see the reward of the previous Mono-Fukun (even if No one can measure this). This will not only give you a program that can be more easily developed and debugged, but also easier to understand and maintain. This is what it is in money. This has a kind of life experience to understand, because when you try to make a segment code becomes more elegant, you are not in a state of productivity. However, please resist people who urge you to drive, because it will only slow down your speed.
2, first seek to move, then ask for fast. Even if you have determined a certain program code is extremely important, and it is an important bottleneck of the system, this guidelines are still established. Simplify design as much as possible, allowing the system to move correctly. If the execution of the program is not fast enough, the performance is measured. Almost you will always find that the "bottleneck" you think is actually not the problem. Take your time on the knife.
3, remember the principle of "breaking". If the problem you explore is too mixed, try to imagine what the basic action will be, and assume that this small piece of things can magically deal with the most difficult part. This "a small piece" thing is actually an object - please write the program code to use the object, then check the object, and then package it into other objects, and so on.
4, distinguish Class developer and Class users (using end programmers). Class users play a "customer" role, do not need (nor, I don't know) Class's underlying mode of operation. Class developers must be a Class design expert and write CLASS to enable it to be used by most newbie programmers as much as possible, and can perform stable execution in the program. A set of libraries is only easy to use in the case of permeability.
5. When you write a Class, try to give a clear name and reduce unnecessary annotations. The interface you give the client programmer should be kept conceptual. Can't make this purpose, when the function's overloading is suitable for the production of intuition, please use it when you use the interface.
6. It is also necessary for your analysis and design to keep Classes in the system to keep its public interfaces to stay at least, and keep the association between these classes and other classes (especially base classes). If your design has received more than this, please ask yourself, is it everything in the entire procedure life? If not so, then maintain them will pay you at a price. Members of the development team have the tendency of anything that is not to maintain "no productivity"; this is a phenomenon that many design methods cannot be explained.
7, let all things are automated as much as possible. Write the program code for test (before you write Class) and let it combine with Class. Please use your Makefile or similar tools to automatically test actions. In this way, as long as the test program is executed, all program changes can be automatically obtained, and an error can be discovered immediately. Since you know the security of the test architecture, you will be more diverse when you find new needs. Keep in mind that the biggest improvement in program language is a built-in test action given from the mechanism of the type, an exception handling. But these functions can only help you reach some degree. When you develop a stable system, you have to verify your own classes or procedures. 8. Write the test code before you write the Class to verify that your Class is designed and complete. If you can't write a test code, you can't know that your Class is possible. The writing test code is usually capable of displaying additional characteristics or constraints__ they do not necessarily always appear in the analysis and design. The test code can also be used as an example program that displays the Class usage.
9, all software design issues can be simplified by "CONCEPTUAL Indirection). The basic law of this software engineering is based on abstract concept, and the concept of abstraction is the main nature of object-oriented programming.
10, indirect layer (indirection) should make sense (and guidelines --9). The meaning referred to here can be as simple as "putting the shared program code in the unique function". If you join the indirect layer (or abstraction, or packaging, etc.) does not make sense, it may be as bad as if there is no proper indirect layer.
11, let Class are as small as possible to cut (atomic). Give each Class single and clear use. If your Classes or your system grows too complicated, please cut complex classes into a relatively simple Classes. The most obvious judgment pointer is the size of the Class: if it is very large, then the opportunity to work too much will be high, then it should be cut. Recommended Class Class is:
1) Complex Switch Statement: Consider the Polymorphism.
2) Many functions have a different type of action: Consider cutting into multiple different (classes).
12, be careful of the lengthy quotation columns (Argument Lists). The lengthy quotation column will make the calling action of the function is not easy to write, read, and maintain. You should try to move the function into a more appropriate class and try to be an object as a quoter.
13, don't repeat again. If a certain program code is constantly appearing in many Derived Class functions, place the program code in a Base Class function and then call in the DeriveD class function. Don't only save the program code space, but also make it easier to modify the program code action. Sometimes you find this common program code can also add a practical function for the interface.
14, be careful of the Switch statement or a string of IF-ELSE clause. Usually this situation represents the so-called "type-check coding". That is to say, which program code is executed, is based on certain types of information (initially, the exact type may not be very obvious). You can usually use inheritance and polymorphism to replace such program code; PolyMorPhical Method calls automatically perform this type of check and provide more reliable and easier expansion.
15. From the design point of view, please find changes in change and separate it and the constant thing. That is to say, finding the elements that may be changed by you in the system, package them in the class. You can learn this idea in "Thinking In Patterns with Java" (you can download free download in www. Bruceeckel. 16. Don't use subclassing to expand the basic function. If an interface element is important to Class, it should be placed in the base class, not until DeriVation (DeriVation) is added. If you add a function during the inheritance process, you should rethink the entire design.
17, less is much. From the minimum interface of Class, it starts to resolve, so that it will keep it small and simple to solve the problem. Don't pre-take all possible ways for your Class used. Once Class is actually used, you will naturally know how you have expanded the interface. However, once the Class is used, you cannot reduce its interface without affecting the customer code. If you want to join more functions, it is no problem - do not affect existing client code, they only need to recompile. But even if the new function replaces the function of the old function, please keep an interface. If you have to extend the interface of both the existing functions by "Joining more quotes", please write an overloaded function with the new quotes; you will not affect any customers with both functions.
18, I read your classes loud, confirm that they are logical. The relationship between base class and derived class is "IS-A" (one) that the relationship between Class and member objects is "HAS-A" (one).
19. When you are hesitant to inheritance or synthesis (combination, composition), ask you to ask yourself, whether you need to go up to the Upcast (Upcast). If you don't need it, please prefer the synthesis (that is, using member objects). This method can eliminate "excessive basic type". If you use inheritance, the user will think they should be transformed upwards.
20. Use data members to represent changes in the value, and use overridden modhod to represent changes in behavior. That is, if you find a Class, there are some status variables, and their functions switched different behaviors based on these variable values, then you may be redesigned, in subclasses and overwriting functions (Overrided Methods) Differences from the middle show.
21, be careful overloading. The function should not select a certain segment code based on the quotation value condition. In this case, you should write two or more overload functions (Overloaded Methods)
22. Exception hierarchies __ is preferably derived from the Java standard anomaly system, then the capture exception can capture a specific exception, and then capture the basic exception. If you join new derivative anomaly, the original client program can still capture it through its base type.
23, sometimes simple aggregation is enough. "Passenger comfort system" on the plane includes several separate elements: seat, air conditioning, video equipment, etc., you will need to have many such things on the plane. Will you declare them as a PRIVATE member and develop a new interface? No, in this example, the element is also part of the public interface, so it is still safe. Of course, simple aggregation is not a solution that is often used, but sometimes it is true. 24. Try to think about the perspective of customer programmers and procedures. Your Class should be designed as much as possible. You should pre-examine the possibility of changes and designs these possible variations, making these changes in the future.
25, be careful of "huge object complications." This is often an upset from the procedural programmer in the OOP field, because they often write a process program and place them into one or two huge objects. Note that except for Application Framework (Application Framework, Translation: A very special, large OO library, helping your architectural program), the object represents the concept of the program, not the program itself.
26. If you have to reach an action in a certain way, please limit the ugly part in a Class.
27, if you have to use some kind of non-portable way to reach an action, abstract it and limit it in a Class. Such a "additional indirect layer" can prevent unmatched parts from diffuse throughout the program. The specific presentation of this approach is the DeSign Pattern.
28, objects should not only use data. Objects should also have a definition definition of behavior. Sometimes it is appropriate to use "data object", but only when the general-purpose container is not applicable, it is appropriate to deliver a group of data items to be packaged.
29. When you want to generate new classes from existing Classes, please take advantage of composition. You should use inheritance only if necessary. If you have inherited at the combination, your design is infiltrating unnecessary complexity.
30. Use the inheritance and function overwriting mechanism to show the differences in behavior, and use the fields (data members) to display the differences in the state. The extreme example of this sentence is to inherit different Classes performances, without using "color" field.
31, beware of Variance. Two objects that have different objects have the same action (or responsibility). There is a natural attraction in the OO world that allows people to inherit another subclass from a Class, which is the benefits brought by inheritance. This is the so-called "variating". However, there is no legitimate reason to allow us to force us to create a superclass / subclass relationship that does not exist. The better solution is to write a shared base class, which makes a shared interface for two derived classes - this way consumes more space, but you can get benefits from the inheritance mechanism as you look forward to. And perhaps it is possible to obtain significant discovery in design.
32, pay attention to the restrictions on inheritance. The clearest and easy-to-understand design is to add functions to inherited Class; in the inheritance process, take off the old function (rather than adding new features) is a suspicious design. However, the rules can break. If you are processed is the old Class library, then in a Class's Subclass restriction function, it may be more efficient than the re-developing structure (which makes new Class to be well commented on the old Class).
33. Use Design Patterns to reduce "naked functionality". For example, if your Class should only output the only one object, please do not complete it with a non-designed technique without design, then write "only one object", take the notice to take the ass to take the ass. . Please pack it into a Singleton (a famous design pattern, can be translated into "single"). If there are many program code in the main program, find out the generation pattern like Factory Method, which makes the price can be used to encapsulate generation actions to reduce "naked naked hidden machine" (Naked FunctionAlity not only makes your program more easy to understand and maintain, but also prevents unexpected maintainers from good intentions. 34. "ANALYSIS Paralysis" due to analysis. Remember, you often have to let the project will continue before getting all the information. And it is understood that the best way to understand the unknown part is usually further, not just a paper. Unless you find a solution, you can't know the solution. Java has built-in firewalls, please let them play. You don't hurt the integrity of the entire system in a single Class or a group of classes.
35. When you think you have already got an excellent analysis, design or implementation, please try it. Bring someone outside the team - he doesn't have to be a consultant, he can be a member of the company's other team. Please examine your results with a fresh gesture, which can find a problem in the stage that can easily modify it, and its harvest is higher than the time and money cost paying due to the drill.
Implementation
36. In general, please abide by the SUN program preparation habits. The price can be found in the following Website: java.sun.com/docs/codeconv/idex.html. This book is as close as possible to these habits. The program code that many Java programmers see is made by these habits. If you stubbornly stay in the past writing style, your (program code) reader will be more hard. Whether you decide what to write habits, please consistent throughout the program. You can find a free tool to rearrange the Java program on Home.wtal.de/software-solutions/jindent.
37. Regardless of the writing style, if your team (or the whole company, it is better) can standardize, then it will make a significant effect. This means that everyone can modify their works without complying with the writing style, which is a fair game. The value of standardization is that the brain force spent when analyzing the program code is small, and thus can focus on the essence of program code.
38. Compliance with standard cases. The first letter of the CLASS name should be uppercase. The first letter of data members, functions, and objects should be lowercase. Every word of all identification names should be connected, all the first first letters should be capitalized. E.g:
THISACLASSNAME
ThisisamethodorfieldName
If you specify a constant initial type (Constant Initializers) at the Static Final basic type, the identification name should be all uppercase, representing a compile period constant.
Packages is a special case, and its name is lowercase, even if the letter is not the first word. Domain name (ORG, NET, EDU, etc.) should be lowercase. (This is a change in Java 1.1 to Java 2) 39. Do not invent "Decorated" Private data member name. Usually this form is to add bottom lines and other characters at the front end, Hungarian NOTATION is the worst demonstration. In this nomenclature, you have to add additional characters to indicate the type, use, location, etc. of the data. It seems that you are using assembly languages and compilers do not provide any coincidence. Such naming methods are easy to confuse and read, nor is it easy to implement and maintain. Let classes and packages are made "Name Scoping".
40. When you draw a generic class, please follow the formal form (CANONICAL FORM). Includes Equals (), hashcode (), Clone () (implemented CLONEABLE) and implements Comparable and Serialiable, and more.
41. For those functions of "acquiring or change the private data value", use Java Beans "GET", "SET", "IS" and other naming habits, even if you don't think you are writing Java Bean. Don't only use your Class to use your Class in the way of use, it is also a standard naming method for such functions, making readers easier to understand. .
42. For every Class you develop, consider adding Static Public Test (), which contains the Class function test code. You don't need to remove the test to incorporate the program into the project. And if you change, you can easily re-execute the test. This program code can also be used as an example of the use of CLASS.
43, sometimes you need to pass inheritance to access the base class's protected member. This may trigger awareness demand for multiple base classes (Multiple Base Types). If you don't need to transform up, you can first derive new Class to perform protected access action, then in all Classes that need to use the above Protected member, the new Class is declared as a member object, not direct inheritance.
44 To avoid purely use the final function for efficient considerations. The final function is used when the program can be moved without fast, and the effectivity meter is not fast enough, and the Equivalent Energy Tool (PROFILER) is used to use the final function.
45. If two Classes creates associations (such as container containers and iterators) for some functional reasons, then try to make it into another Class's internal hidden class (INNER CLASS). This not only emphasizes the relationship between the two, but also enables the same Class name to be reused in single package by "nested in another class". The Java container library defines an inner Iterator Class in each container class, thus providing a container common interface. Another reason for using internal hidden class is to make it part of the Private implementation. Here, the hidden class will benefit the information hide, rather than providing ribs to the above Class relevance, nor to prevent namspace pollution.
46, you have to pay attention to those highly coupled classes. Please consider the benefits of inner classes as programs and maintenance. Internal hidden use is not to remove the coupling between Classes, but to make the coupling relationship more obviously more convenient. 47, do not be a victim of "prematurely optimization". That will make people nerve disorder. Especially in the early stages of system construction, don't worry, don't write (or avoid) Native Methods, do you want to declare some numbers to Final, do not adjust program code efficiency, etc. Your main problem should be to prove the correctness of the design unless the design itself needs some level of efficiency.
48, let the range (scope, scope) as soon as possible, such a visual range and life of the object will be as small as possible. This method can reduce "objects used in error places, and thereby hide difficult to spotted bugs". Suppose you have a container, and a program that visits the container. If you copy the program code, use it for your new container, you might be unclear as a new container's interview with the size of the new container. If the old container is not within the access range, you can find such an error.
49. Use the container provided by the Java standard library. Please be familiar with their usage. You will thus greatly enhance your productivity. Please select ArrayList to handle the sequence, select the HashSet to handle the collection (SETS), select HashMap to handle the associated array (Associative Arrays), select LinkedList (not STACK) to handle Shacks and Queues.
50. For a strong Robust program, each composition must be strong. Please use the strong improvement tools provided by Java in each class you wrote: Access permissions, exceptions, type inspection, and more. In this way, you can safely move to an abstract next level when constructing the system.
51, I would like to have an error in the compile period, or do not have an error during the execution period. Try the problem of local treatment in the closer problem. Please take priority to the problem of "throwing anomalies" and capture exceptions in the closest process of processing an exception. Please do this at this stage you can do it to the exception; if you can't solve the problem, you should throw an exception again.
52, the function is defined. The function should be a short, "describing and implementing a separate portion of the Class interface". Excessive and complex functions are not only difficult to maintain, but the maintenance cost is also high. Maybe it tries to do too many things. If you find this type of function, it should be cut into a multiphase function. This function also reminds you to write new Class. Small functions can also be used repeated in your Class. (Sometimes the function must be very talented, but they should only do something.)
53, keep "private" as much as possible. Once you open an outline of the library (Method, Class or Field). You can no longer be removed. Because if they remove them, an existing program code will be destroyed so that they must be re-written or redesigned. If you only publicize the necessary part, you can change the other things without causing harm. Design will always evolve, so this is a very important degree of freedom. In this way, the impact caused by the DERIVED CLASS is lowered by the implementation of the impact caused by the Derived Class. In multi-threaded environments, privacy is important - only the private data can be protected without the use of UN-SYNCHRONIZED (uncontrolled control).
54. A large number of annotations and use Javadoc's "annotation grammar" to generate a documentation. However, the annotation should give the program code real meaning; if it is just that the program code has been clearly expressed, it is very annoying. Note that usually the name of Java Class and its function is very long, and it is to reduce the amount of annotation. 55, avoid using "Magic Digital", that is, the number written in the program code - if you want to change them, they will become your nightmare, because you will never know "100" representative "Array size" or other things. You should generate a descriptive constant degree name and use this constant name in the program. This makes the program easier to understand and easier to maintain.
56. When writing a constructor, consider an abnormal state. In the best context, the constructor does not perform any action that will throw an abnormality. Under the court, the Class only inherits the strong (or synthetic self) strong (Robust) Classes, so if any abnormality is thrown, it is not necessary to clean. In other cases, you have to clean up the synthesis of Classes in the Finally clause. If a constructor will fail, the appropriate action is to throw an exception, so that the caller does not blindly think that the object has been properly generated and continues.
57. If your class needs to clean up after the "customer programmer running object", the cleaning action will be cleaned, put it in a single definition in a clear function. It is best to make its name Cleanup () so that you can tell others. In addition, put the Boolean flag into the Class to represent whether the object has been cleaned up, so that Finalize () can be verified to test the death conditions (see Chapter 4).
58, Finalize () can only be used for the test of object death conditions (please refer to Chapter 4), and it is good for debugging. Special circumstances may be needed to release some memory that will not be recovered by garbage. Because the garbage collector may not be aroused to handle your object, you can't use Finalize () to perform the necessary cleanup action. Based on this reason, you have to develop your own "cleanup" function. In class finalize (), check that the confirmation object is indeed cleared and throws an exception derived from Runtime Exception when the object has not been cleaned. Before using this architecture, please confirm that Finalize () can be actually moved on your system (this may need to call System.gc () to confirm).
59. If an object must be cleaned in a specific range (Scope), it must be reclaimed by the garbage collection mechanism, use the following method; initialize the object, immediately enter one of the FINALLY clause During the TRY section. The Finally clause will cause cleaning action.
60. When you override Finalize () in the inheritance process, remember to call Super. Finalize (). But if your "Direct Layer SUPERCLASS" is Object, you don't need this action. You should let super.finalize () become the last move of overridden's Finalize () instead of the first action to ensure that Base Class's components are still available when you need them.
61. When you write a fixed-size object container, convert them into array - especially when returning to this container from a function. In this way, you can get the benefits of "Compile Type Item Test" in arrays, and array recipients may not need to "transform objects in arrays". Note that the Base Class (Java. Util. Collection) of the container library has two toARRAY (), which can achieve this purpose. . 62. Between Interface and Abstract Class (abstract classes), prioritizes. If you know that something is about to be designed as a base class, your first choice should be to become Interface; you should change it to Abstract Class. Interface only when you have a function or data member. "What is the action of the client," Class is compared to put the center of gravity on the implementation details.
63. Only the only necessary action in the constructor: set the object to the appropriate state. Avoid calling other functions (except for the Final function), because these functions may be overwritten by other people thus to make you unpredictable results during the construction process (see Chapter 7 to achieve more detailed information). Small and simple constructor is more impossible to throw an abnormality or cause problems.
64. In order to avoid a very discivous experience, please confirm that each name in your classpath is only one unsteaded in the Packages. Otherwise, the compiler will find another name of the same name and return an error message. If you doubt your classpath, try to find the same name. Class file from each starting point in ClassPath. It is best to put all Classes in the Packages.
65, pay attention to the overloading of accidents. If you overwrite the base class function, you don't have correctly spell your name, then a new function is added instead of overlying the original function. However, the situation is completely legal, so you will not get any error messages from the compiler or execution period - your program code is just the correct effect, so.
66. Before the heart is prematurely optimized. Let the program move, let it be fast - but only in you must (that is, if the program is proven to be able to experience the performance bottleneck on a certain program code). Unless you have used the Effective Energy Tool (Profiler) to find the bottleneck, you may be just wasting your time. The "hidden cost" of the efficiency adjusted is to make your program code more unread, it is more difficult to maintain.
67. Remember that the program code is read more than the time it is written. Clear design can make it easy to understand. Note, details, examples are invaluable. These things can help you and your successor. If there is no other information, then the documentation on the Java online finds some useful information, the frustration you encounter should be enough to let you believe this.