A Lambda Calculus intepreter in Java
October 27, 2015 • Alex Leighton
I’ve added a utility class for Validating preconditions, heavily inspired by the Validate class found in Apache Commons.
/**
* Throws {@link NullPointerException} if the given object is null, returning the given object
* if it is not null. The thrown NullPointerException will contain a message created by passing
* msg and args to {@link String#format(String, Object...)}.
* @param obj The object to check against null.
* @param msg The format string to use as the exception message if obj is null.
* @param args The arguments to msg for use if obj is null.
* @return obj if it is not null.
* @throws NullPointerException if obj is null.
*/
public static <T> T notNull(final T obj, final String msg, final Object... args) {
if (obj == null) {
throw new NullPointerException(String.format(msg, args));
}
return obj;
}/src/alonzo/common/Validate.java
Semantic correctness is an important part of software design for me. I use strong typing because it’s a cheap (cheaper than finding them at runtime) way of discovering and preventing bugs. In keeping with this ideology, I believe in failing fast. Discovering a bug or error during the running of a program as soon as it appears makes debugging easier (due to quicker root-causing). Ensuring that objects are constructed correctly or that objects to be used abide by expectations makes writing logic around them easier.
I use Validate to ensure that expected preconditions hold, or else fail immediately. Typically I will use Validate assertions to guarantee that an object is correct on construction, or else fail construction. This makes it harder to pass around broken objects, another aspect of failing fast. So far I’ve only needed to check for null. However, it is highly likely that I will be adding to this class in the future.