Tuesday, October 13, 2020

Java 15: Sealed Classes

Java 15 introduces Sealed Classes, a preview language feature, that allows classes/interfaces to restrict which other classes/interfaces may extend or implement them. Here is an example:

public sealed class Vehicle permits Car, Truck, Motorcycle { ... }

final class Car extends Vehicle { ... }
final class Truck extends Vehicle { ... }
final class Motorcycle extends Vehicle { ... }

In the example above, Vehicle is a sealed class, which specifies three permitted subclasses; Car, Truck and Motorcycle.

The subclasses must be:

  • in the same package or module as the superclass. You can even define them in the same source file as the superclass (if they are small in size), in which case the permits clause is not required because the compiler will infer them from the declarations in the file.
  • declared either final (i.e. cannot be extended further), sealed (i.e. permit further subclasses in a restricted fashion) or non-sealed (i.e. open for extension by any class).

Sealing serves two main purposes:

  1. It restricts which classes or interfaces can be a subtype of a class or interface and thus preserves the integrity of your API.
  2. It allows the compiler to list all the permitted subtypes of a sealed type (exhaustiveness analysis), which will (in a future Java release) enable switching over type patterns in a sealed type (and other features). For example, given the following switch statement, the compiler will detect that there is a case statement for every permitted subclass of Vehicle (so no default clause is needed) and it will also give an error if any of them are missing:
    int doSomething(Vehicle v) {
      return switch (v) {
          case Car c -> ...
          case Truck t -> ...
          case Motorcycle m -> ...
      };
    }

Monday, July 20, 2020

kdb+/q - Try Catch

Programming languages typically have a try-catch mechanism for dealing with exceptions. The try block contains the code you want to execute and the catch block contains the code that will be executed if an error occurs in the try block.

Here is an example of a simple try-catch block in Java, which attempts to parse a string into an int and returns -1 if there is an error.

try {
    return Integer.parseInt(x);
} catch (NumberFormatException e) {
    e.printStackTrace();
    return -1;
}

In this post, I will describe the try-catch equivalent for exception handling in the q programming language.

.Q.trp[f;x;g] - for unary functions

For unary functions, you can use .Q.trp (Extend Trap), which takes three arguments:

  1. f - a unary function to execute
  2. x - the argument of f
  3. g - a function to execute if f fails. This function is called with two arguments, the error string x and the backtrace object y

For example:

// Define a function which casts a string to int
parseInt:{[x] "I"$x}

// Define an error function which prints the stack trace and returns -1
// Note: .Q.sbt formats the backtrace object and 2@ prints to stderr
g:{[x;y] 2@"Error: ",x,"\nBacktrace:\n",.Q.sbt y;-1i}

// Try calling the function (wrapped by .Q.trp) with a valid argument
.Q.trp[parseInt;"123";g]
123i

// Try calling the function (wrapped by .Q.trp) with an invalid argument
// The error function is called and the stack trace is printed
.Q.trp[parseInt;`hello;g]
Error: type
Backtrace:
  [2]  parseInt:{[x] "I"$x}
                        ^
  [1]  (.Q.trp)

  [0]  .Q.trp[parseInt;`hello;g]
       ^
-1i

Note: An alternative is to use Trap At which has syntax @[f;x;e] but you won't get the backtrace, so it's better to use .Q.trp.

.[f;args;e] - for n-ary functions

.Q.trp only works for unary functions. For functions with more than one argument, you need to use Trap which has the syntax .[f;args;e]. The error function e does not take any arguments, which means no backtrace available. For example:

// Define a ternary function that sums its arguments
add:{[x;y;z] x+y+z}

.[add;1 2 3;{2@"Failed to perform add";-1}]
6

.[add;(1;2;`foo);{2@"Failed to perform add\n";-1}]
Failed to perform add
-1

Friday, July 10, 2020

Compute MD5 Checksum Hash on Windows and Linux

Use the following commands to print out the MD5 hash for a file.

On Windows:

> CertUtil -hashfile myfile.txt MD5
MD5 hash of file myfile.txt:
76383c2c0bfca944b57a63830c163ad2
CertUtil: -hashfile command completed successfully.

On Linux/Unix:

$ md5sum myfile.txt
76383c2c0bfca944b57a63830c163ad2 *myfile.txt

Sunday, May 17, 2020

Java 14: Helpful NullPointerException Messages

A new JVM option, -XX:+ShowCodeDetailsInExceptionMessages, has been introduced in Java 14, in order to provide helpful NullPointerException messages showing precisely what was null when a NullPointerException occurred. For example, consider the code below:

var name = library.get("My Book").getAuthor().getName();

Before Java 14, the JVM would only print the method, filename, and line number that caused the NPE:

Exception in thread "main" java.lang.NullPointerException
 at Library.main(Library.java:7)

As you can tell, this error message is not very useful because it is impossible to determine which variable was actually null (without using a debugger). Was it the library, the book returned from the library, or the author of the book?

In Java 14, after enabling -XX:+ShowCodeDetailsInExceptionMessages, you will get the following message:

Exception in thread "main" java.lang.NullPointerException: 
Cannot invoke "Author.getName()" because the return value of "Book.getAuthor()" is null
 at Library.main(Library.java:7)

The exception message pinpoints what was null (Book.getAuthor()) and also displays the action that could not be performed as a result of this (Author.getName()).

Monday, April 13, 2020

Java 14: Pattern Matching for instanceof

Java 14 introduces Pattern Matching for instanceof, another preview language feature, that eliminates the need for casts when using instanceof. For example, consider the following code:

if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.length());
}

This code can now be rewritten as:

if (obj instanceof String s) {
    System.out.println(s.length());
}

As shown above, the instanceof operator now takes a "binding variable" and the cast to String is no longer required. If obj is an instance of String, then it is cast to String and assigned to the binding variable s. The binding variable is only in scope in the true block of the if-statement.

In particular, this feature makes equals methods a lot more concise as shown in the example below:

@Override
public boolean equals(Object obj) { 
  return this == obj || 
    (obj instanceof Person other) && other.name.equals(name);
}

This feature is an example of pattern matching, which is already available in many other programming languages, and allows us to conditionally extract components from objects. It opens the door for more general pattern matching in the future which I am very excited about!