common mistakes best practices coding standards

Upload: madduri-venkateswarlu

Post on 30-May-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    1/21

    Common mistakesBest Practices

    Coding standards

    Govind Krishna Mekala

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    2/21

    What we wont cover

    J2ee/EJB antipatternsDesign Patterns

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    3/21

    What we will cover

    Interactive session with lots of exampleson:

    Core Java mistakes and solutions.

    Best Practices for Java and JDBC.

    Why coding standards are so

    important?

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    4/21

    Object Creation

    Static factory methods are moreappealing than constructors.Public static Boolean valueOf(boolean b) {

    return (b?Boolean.TRUE:Bolean.FALSE);}

    Use private constructor when defining a

    class for grouping static fields andmethods.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    5/21

    Avoid creating duplicate objects:String s = new String(No);

    Eliminate obsolete reference by nullingout to avoid memory leaks due tounitentional object reference. (Specially incollections and Maps).

    Nothing time critical should ever be doneby a finalizer. Never depend on Finalizerand we cant time GC. Use finalizer as

    safe net to terminate noncritical nativeresources without forgettingsuper.finalize.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    6/21

    Providing a good toStringimplementation makes your class muchmore pleasant to use.

    System.out.println(Failed to connect: +phoneNumber);

    Always override hashCode method whenyou override equals. Failure to do so will

    result in violation of the general contractfor Object.hashCode which will preventyour class from functioning properly withconjunction with all hash-basedcollections, including HashMap, HashSetand HashTable.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    7/21

    Composition vs Inheritance

    Lets discuss this firstNever extend a class unless documented todo so. Always document if you write a classfor extending. Reason: Subclasses will breakwhen super class changes. Unintentional trapfor super class just because some ignorantprogrammers written several subclasses.

    Must read link:http://www.artima.com/designtechniques/compoinh.html

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    8/21

    Prefer Interface over Abstract

    Multiple inheritance problem.Interface enables safe, power funtionalityenhancement without using hierarchical typeframework.

    You can combine the virtue of interface andabstract classes by proving as abstractskeleton implementation class to go with

    each nontrivial interface you export. E.gAbstractCollection, AbstractSet,AbstractList..

    Comparative analysis (Not official):

    http://mindprod.com/jgloss/interfacevsabstract.html

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    9/21

    Use overloading carefully.Return zero-length arrays instead of nulls.

    Minimize the Use of Finalizers

    Avoid float and double if exact answersare required. Use BigDecimal, int or longfor monetary calculations.

    System.out.println(1.03 0.42);

    System.out.println(1.00 - .10);

    Money matters in financial calculations.htm

    //0.6100000000000001

    //0.09999999999999995

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    10/21

    Avoid string concatenation for morethan few strings. Use stringBufferinstead as string is immutable.

    Refer to objects by their interfaces ifappropriate interface exists.

    (flexibility).List myList = new vector();

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    11/21

    Exception Handling common

    mistakes

    Empty Catch BlocksLoss of Stack Information. Use exceptionchaining (or nesting) supported in JDK 1.4

    Incomprehensible and IncompleteException Logs.

    Because, a catch statement that uses asuperclass will catch exceptions of that type

    plus any of its subclasses. So, the subclasswould never be reached if it come after itssuperclass. For example,

    ArithmeticException is a subclass ofException

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    12/21

    Enhanced Exception Handling

    Support in Java 1.4

    Exception Chaining: In Java version 1.4support for it has therefore been built intothe uppermost exception base class:

    Throwable( String message, Throwable cause )

    Throwable( Throwable cause )

    Assertions: They make it possible toimprove software quality by abundant use ofruntime checks for internal preconditions,postconditions and invariants similar to Cassertion macros.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    13/21

    Thread Safety

    Synchronize access to shared mutable data.In a multi-threaded environment, anymutable data visible to more than one threadmust be referenced within a synchronized

    block. This includes all primitive data. All getand set methods for shared data which canchange must be synchronized.

    It is a misconception that all primitives exceptlong and double do not need synchronizedaccess.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    14/21

    Thread Safety cont..

    Avoid excessive synchronization. Excessivesynchronization might causes deadlock. Do as little as possible inside synchronized region.

    Obtain the lock, examine the shared data,

    transform the data as necessary, and drop thelock.

    If a class could be used both in circumstancesrequiring synchronization and circumstances

    where synchronization not required, provide boththe variants through wrapper class or subclasswith synchronization.

    To avoid deadlock and data corruption, never call

    an alien method from within synchronized region.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    15/21

    Thread Safety cont..

    Never invoke wait outside a loop and prefernotifyAll in preference to notify.

    Dont depend on thread scheduler and threadpriorities. They are not portable across VM

    and OS.Avoid thread groups. Thread groups wereintroduced for isolating applets for security

    which didnt fulfill the promise. The APIs toget list of active threads and subgroups arebuggy. Thread groups are obsolete.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    16/21

    Thread Safety cont..

    Singleton pitfalls. To decide whether to createa singleton class, first ask these questions: 1. Does there need to one global entry point to

    this class?

    2. Should there be fixed number of instance inVM?

    Never use singleton class as global variables asthey might become non singleton.

    Read link:http://www.artima.com/designtechniques/threadsafety.html

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    17/21

    JDBC

    Use connection pooling.

    Choose appropriate isolation levels.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    18/21

    JDBC Cont..

    Use Statement pooling.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    19/21

    JDBC Cont..

    Statements versus Prepared Statements:When to Use What?

    Tune the SQL to minimize the data returned

    (e.g. not 'SELECT *').Avoid the Usage of Metadata Methods (e.gDatabaseMetaData.getColumns() whenever

    Possible. They are expensive.Try to combine queries and batch updates.

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    20/21

    JDBC Cont..

    Use stored procedures.Cache data to avoid repeated queries.

    Close resources (Connections, Statements,ResultSets) when finished with.

    Select the fastest JDBC driver.

    http://www.oreil ly.com/catalog/jorajdbc/chapter/ch19.html#74469

    Link to read:

    http://www.precisejava.com/javaperf/j2ee/JDBC.htm

  • 8/14/2019 Common Mistakes Best Practices Coding Standards

    21/21

    Why coding conventions are

    important?

    We all have our own coding style but ourcode is not a piece of art for others.

    Use most widely used conventions formethod, fields naming. Refer Sun site.

    Make set of coding standards mandatoryrelevant to your product and projectmaintenance.

    Document inheritance, overload, staticchecked exceptions without fail.