Implementation with Java

Implementation with Java

From:http://jcsc.sourceforge.net

  1. In general, follow the Sun coding conventions.These are available at java.sun.com/docs/codeconv/index.html (the code in this book follows these conventions as much as I was able). These are used for what constitutes arguably the largest body of code that the largest number of Java programmers will be exposed to. If you doggedly stick to the coding style you’ve always used, you will make it harder for your reader. Whatever coding conventions you decide on, ensure that they are consistent throughout the project. There is a free tool to automatically reformat Java code at http://jalopy.sourceforge.net. You can find a free style checker at http://jcsc.sourceforge.net.
  2. Whatever coding style you use, it really does make a difference if your team (and even better, your company) standardizes on it.This means to the point that everyone considers it fair game to fix someone else’s coding style if it doesn’t conform. The value of standardization is that it takes less brain cycles to parse the code, so that you can focus more on what the code means.  
  3. Follow standard capitalization rules.Capitalize the first letter of class names. The first letter of fields, methods, and objects (references) should be lowercase. All identifiers should run their words together, and capitalize the first letter of all intermediate words. For example:ThisIsAClassName,thisIsAMethodOrFieldNameCapitalize all the letters (and use underscore word separators) of static final primitive identifiers that have constant initializers in their definitions. This indicates that they are compile-time constants.Packages are a special case—they are all lowercase letters, even for intermediate words. The domain extension (com, org, net, edu, etc.) should also be lowercase. (This was a change between Java 1.1 and Java 2.)  
  4.  Don’t create your own “decorated” private field names.This is usually seen in the form of prepended underscores and characters. Hungarian notation is the worst example of this, where you attach extra characters that indicate data type, use, location, etc., as if you were writing assembly language and the compiler provided no extra assistance at all. These notations are confusing, difficult to read, and unpleasant to enforce and maintain. Let classes and packages do the name scoping for you. If you feel that you must decorate your names to prevent confusion, your code is probably too confusing anyway and should be simplified.  
  5. Follow a “canonical form”.when creating a class for general-purpose use. Include definitions for equals( ), hashCode( ), toString( ), clone( ) (implement Cloneable, or choose some other object copying approach, like serialization), and implement Comparable and Serializable.  
  6. Use the JavaBeans “get,” “set,” and “is” naming conventions for methods that read and change private fields, even if you don’t think you’re making a JavaBean at the time. Not only does it make it easy to use your class as a Bean, but it’s a standard way to name these kinds of methods, so it will be more easily understood by the reader.  
  7. For each class you create, include JUnit tests for that class (see www.junit.org, and examples in Chapter 15). You don’t need to remove the test code to use the class in a project, and if you make any changes, you can easily rerun the tests. This code also provides examples of how to use your class.  
  8. Sometimes you need to inherit in order to access protected members of the base class. This can lead to a perceived need for multiple base types. If you don’t need to upcast, first derive a new class to perform the protected access. Then make that new class a member object inside any class that needs to use it, rather than inheriting.  
  9. Avoid the use of final methods for efficiency purposes. Use final only when the program is running, but not fast enough, and your profiler has shown you that a method invocation is the bottleneck.  
  10. If two classes are associated with each other in some functional way (such as containers and iterators), try to make one an inner class of the other. This not only emphasizes the association between the classes, but it allows the class name to be reused within a single package by nesting it within another class. The Java containers library does this by defining an inner Iterator class inside each container class, thereby providing the containers with a common interface. The other reason you’ll want to use an inner class is as part of the private implementation. Here, the inner class is beneficial for implementation hiding rather than the class association and prevention of namespace pollution noted above.  
  11. Anytime you notice classes that appear to have high coupling with each other, consider the coding and maintenance improvements you might get by using inner classes. The use of inner classes will not uncouple the classes, but rather make the coupling explicit and more convenient.  
  12. Don’t fall prey to premature optimization. This way lies madness. In particular, don’t worry about writing (or avoiding) native methods, making some methods final, or tweaking code to be efficient when you are first constructing the system. Your primary goal should be to prove the design. Even if the design requires a certain efficiency, first make it work, then make it fast.  
  13. Keep scopes as small as possible so the visibility and lifetime of your objects are as small as possible. This reduces the chance of using an object in the wrong context and hiding a difficult-to-find bug. For example, suppose you have a container and a piece of code that iterates through it. If you copy that code to use with a new container, you may accidentally end up using the size of the old container as the upper bound of the new one. If, however, the old container is out of scope, the error will be caught at compile time.  
  14. Use the containers in the standard Java library. Become proficient with their use and you’ll greatly increase your productivity. Prefer ArrayList for sequences, HashSet for sets, HashMap for associative arrays, and LinkedList for stacks (rather than Stack, although you may want to create an adapter to give a stack interface) and queues (which may also warrant an adapter, as shown in this book). When you use the first three, you should upcast to List, Set, and Map, respectively, so that you can easily change to a different implementation if necessary.  
  15. For a program to be robust, each component must be robust. Use all the tools provided by Java—access control, exceptions, type checking, synchronization, and so on—in each class you create. That way you can safely move to the next level of abstraction when building your system.  
  16. Prefer compile-time errors to run-time errors. Try to handle an error as close to the point of its occurrence as possible. Catch any exceptions in the nearest handler that has enough information to deal with them. Do what you can with the exception at the current level; if that doesn’t solve the problem, rethrow the exception.  
  17. Watch for long method definitions. Methods should be brief, functional units that describe and implement a discrete part of a class interface. A method that is long and complicated is difficult and expensive to maintain, and is probably trying to do too much all by itself. If you see such a method, it indicates that, at the least, it should be broken up into multiple methods. It may also suggest the creation of a new class. Small methods will also foster reuse within your class. (Sometimes methods must be large, but they should still do just one thing.)  
  18. Keep things as “private as possible.” Once you publicize an aspect of your library (a method, a class, a field), you can never take it out. If you do, you’ll wreck somebody’s existing code, forcing them to rewrite and redesign. If you publicize only what you must, you can change everything else with impunity, and since designs tend to evolve, this is an important freedom. In this way, implementation changes will have minimal impact on derived classes. Privacy is especially important when dealing with multithreading—only private fields can be protected against un-synchronized use. 
  19. Classes with package access should still have private fields, but it usually makes sense to give the methods of package access rather than making them public.  
  20. Use comments liberally, and use the javadoc comment-documentation syntax to produce your program documentation. However, the comments should add geniune meaning to the code; comments that only reiterate what the code is clearly expressing are annoying. Note that the typical verbose detail of Java class and method names reduce the need for some comments.  
  21. Avoid using “magic numbers”—which are numbers hard-wired into code. These are a nightmare if you need to change them, since you never know if “100” means “the array size” or “something else entirely.” Instead, create a constant with a descriptive name and use the constant identifier throughout your program. This makes the program easier to understand and much easier to maintain.  
  22. When creating constructors, consider exceptions. In the best case, the constructor won’t do anything that throws an exception. In the next-best scenario, the class will be composed and inherited from robust classes only, so they will need no cleanup if an exception is thrown. Otherwise, you must clean up composed classes inside a finally clause. If a constructor must fail, the appropriate action is to throw an exception, so the caller doesn’t continue blindly, thinking that the object was created correctly.  
  23. Inside constructors, do only what is necessary to set the object into the proper state. Actively avoid calling other methods (except for final methods), because those methods can be overridden by someone else to produce unexpected results during construction. (See Chapter 7 for details.) Smaller, simpler constructors are less likely to throw exceptions or cause problems.  
  24. If your class requires any cleanup when the client programmer is finished with the object, place the cleanup code in a single, well-defined method, with a name like dispose( ) that clearly suggests its purpose. In addition, place a boolean flag in the class to indicate whether dispose( ) has been called so that finalize( ) can check for “the termination condition”.
  25. The responsibility of finalize( ) can only be to verify “the termination condition” of an object for debugging. (See Chapter 4.) In special cases, it might be needed to release memory that would not otherwise be released by the garbage collector. Since the garbage collector might not get called for your object, you cannot use finalize( ) to perform necessary cleanup. For that you must create your own dispose( ) method. In the finalize( ) method for the class, check to make sure that the object has been cleaned up and throw a class derived from RuntimeException if it hasn’t, to indicate a programming error. Before relying on such a scheme, ensure that finalize( ) works on your system. (You might need to call System.gc( ) to ensure this behavior.)
  26. If an object must be cleaned up (other than by garbage collection) within a particular scope, use the following idiom: initialize the object and, if successful, immediately enter a try block with a finally clause that performs the cleanup.  
  27. When overriding finalize( ) during inheritance, remember to call super.finalize( ). (This is not necessary if Object is your immediate superclass.) You should call super.finalize( ) as the final act of your overridden finalize( ) rather than the first, to ensure that base-class components are still valid if you need them.  
  28. When you are creating a fixed-size container of objects, transfer them to an array, especially if you’re returning this container from a method. This way you get the benefit of the array’s compile-time type checking, and the recipient of the array might not need to cast the objects in the array in order to use them. Note that the base-class of the containers library, java.util.Collection, has two toArray( ) methods to accomplish this.  
  29. Choose interfaces over abstract classes. If you know something is going to be a base class, your first choice should be to make it an interface, and only if you’re forced to have method definitions or member variables should you change it to an abstract class. An interface talks about what the client wants to do, while a class tends to focus on (or allow) implementation details.  
  30. To avoid a highly frustrating experience, make sure that there is only one unpackaged class of each name anywhere in your classpath. Otherwise, the compiler can find the identically-named other class first, and report error messages that make no sense. If you suspect that you are having a classpath problem, try looking for .class files with the same names at each of the starting points in your classpath. Ideally, put all your classes within packages.  
  31. Watch out for accidental overloading. If you attempt to override a base-class method and you don’t quite get the spelling right, you’ll end up adding a new method rather than overriding an existing method. However, this is perfectly legal, so you won’t get any error message from the compiler or run-time system; your code simply won’t work correctly.  
  32. Watch out for premature optimization. First make it work, then make it fast—but only if you must, and only if it’s proven that there is a performance bottleneck in a particular section of your code. Unless you have used a profiler to discover a bottleneck, you will probably be wasting your time. The hidden extra cost of performance tweaks is that your code becomes less understandable and maintainable.  
  33. Remember that code is read much more than it is written. Clean designs make for easy-to-understand programs, but comments, detailed explanations, tests, and examples are invaluable. They will help both you and everyone who comes after you. If nothing else, the frustration of trying to ferret out useful information from the JDK documentation should convince you. 

转载于:https://www.cnblogs.com/iiiDragon/p/3271898.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值