Effective Java

  • This section provides the list of items in the book Effective Java by Joshua Bloch.

  • These are some best practices when programming with Java.

Creating and Destroying Objects

  1. Consider static factory methods instead of constructors

  • Unlike constructors, static factory methods have names.

  • They are not required to create a new object each time they are invoked.

  • They can return an object of any subtype of their return type.

  • However, classes without public or protected constructors cannot be subclassed.

  • The returned object can vary for each invokation as a function of the input parameters.

  • The returned object need not exist when the class containing the method is written (e.g. JDBC).

  1. Consider a builder when faced with many constructor parameters

  • The Builder pattern simulates named optional parameters found in Python and Scala.

  • It can be used for class hierarchies.

  • It is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

  1. Use try-with-resources instead of try-finally

  • Instead of using a try-finally block and closing whatever resource we are refering to, we use a simple try {} block on the resource which must have an AutoCloseable interface implementation.

1// try-with-resources on a single resource
2static String firstLineOfFile(String path) throws IOException {
3  try ( BufferedReader br = new BufferedReader(
4          new FileReader(path)) ) {
5            return br.readLine();
6          }
7}
 1// try-with-resources on multiple resources
 2static void copy(String src, String dst) throws IOException {
 3  try (
 4    InputStream in = new FileInputStream(src);
 5    OutputStream out = new FileOutputStream(dst);
 6    ) {
 7      byte[] buf = new byte[BUFFER_SIZE];
 8      int n;
 9      while ((n = in.read(buf)) >= 0)
10        out.write(buf, 0, n);
11    }
12}
1try ( Scanner scanner = new Scanner(new File("test.txt")) ) {
2  while (scanner.hasNext()) {
3    System.out.println(scanner.nextLine());
4  }
5} catch (FileNotFoundException fnfe) {
6  fnfe.printStackTrace();
7}