Thursday, May 6, 2010

Java Tips

  1. The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used. 
  2. Nearly every local variable declaration should contain an initializer. If you don’t yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do.
  3. Every programmer should be familiar with the contents of java.lang, java.util, and, to a lesser extent, java.io.
  4. The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.use BigDecimal, int, or long for monetary calculations
  5. Instance fields should never be public. Classes with public mutable fields are not thread-safe.If a class cannot be made immutable, limit its mutability as much as possible. Reducing the number of states in which an object can exist makes it easier to reason about the object and reduces the likelihood of errors. Therefore, make every field final unless there is a compelling reason to make it non-final.
  6. Escape analysis: if you create an object in a method and Java can tell that no references to it "escape"--that is, that the object can't be referenced by another thread and it won't exist after the method returns--then the JVM will allocate it on the stack (or equivalent) and it will avoid using locks even if the object's class or methods are declared "synchronized". -XX:+DoEscapeAnalysis
  7. Excellent Summary of GC
  8. The best reason not to write finalizers  is that they are not guaranteed to be run.
  9. Inner vs Nested Class
  10. Design Principles from Design Patterns
  11. The strategy pattern uses composition instead of inheritance. In the strategy pattern behaviors are defined as separate interfaces and specific classes that implement these interfaces. Specific classes encapsulate these interfaces. This allows better decoupling between the behavior and the class that uses the behavior. The behavior can be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes. Behaviors can also be changed at run-time as well as at design-time.       http://en.wikipedia.org/wiki/Strategy_pattern            
  12. Why do most system architects insist on first coding to an interface??
  13. you should export the constant with a noninstantiable utility class.
  14. Interfaces should be used only to define types. They should not be used to export constants.