Convert Dynamic to Static Construction

Refactoring contributed by Gerard M. Davison

You have code that loads other classes dynamically. This can introduce a un-waranted overhead and can produce code that is more fragile.

Replace the dynamic class loading with static code.




   try
   {
      DataProvider dp = (DataProvider)
         Class.forName("org.davison.data.jdbc.JDBCProvider").newInstance();
   }
   catch (IllegalAccessException iae)
   {
      // Convert exception to error to preseve the interface.
      //
      
      throw new IllegalAccessError(iae.getMessage());
   }
   catch (InstantiationException ie)
   {
      // Convert exception to error to preseve the interface.
      //
      
      throw new InstantiationError(ie.getMessage());      
   }
   catch (ClassNotFoundException cnfe)
   {
      // Convert exception to error to preseve the interface.
      //

      throw new NoClassDefFoundError(cnfe.getMessage());
   }




   import org.davison.data.jdbc.JDBCProvider;

   .
   .
   .
   
   DataProvider dp = new JDBCProvider();

Motivation

In some cases code is written with dynamic dependencies between parts of the code by utilising Java ability to load and instantiate arbitrary classes. If not properly managed, this can cause run-time errors. This design can impart a performance penalty because of the extra levels of indirection. It can also prevent the compiler from detecting certian types of error.

Mechanics

Example

| Refactoring Home | | Alphabetical List |