Utility class
In computer programming, a utility class is a class that defines a set of methods that perform common, often re-used functions. Most utility classes define these common methods under static (see Static variable) scope. Examples of utility classes include java.util.Collections which provides several utility methods (such as sorting) on objects that implement a Collection (java.util.Collection ).
Example
DbConnection.java(util class):- import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public final class DbConnection { public static Connection con; public static String uId = "User_id"; public static String pwd = "password"; private DbConnection() { // Utility classes should always be final and have a private constructor } public static Connection createConnection() { try { // Loading the driver Class.forName("oracle.jdbc.driver.OracleDriver"); // Creating a connection String conUrl = "jdbc:oracle:thin:@Host_id:Port:SID"; con = DriverManager.getConnection(conUrl, uId, pwd); } catch(ClassNotFoundException e) { System.out.println("Driver not found"); } catch (SQLException sq1ex) { System.out.println("Connection exception" + sq1ex); } return con; } public static void closeConnection(Connection con) { if(con != null) { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void closeStatement(PreparedStatement ps) { if(ps != null) { try { ps.close(); } catch (SQLException e) { // TODO Auto-generated a catch block e.printStackTrace(); } } } }
See also
- Helper class
- Utility pattern
- BaseBean anti-pattern
External links
- Utility Pattern: For a utility class, which does not require instantiation and only has static methods, use a private constructor
- OOP Alternative to Utility Classes: explains why utility classes may be considered harmful in a pure object-oriented design