Type safety in Nice

Why programs written in Nice have less bugs

Daniel Bonniot


Table of Contents

Introduction
Existing safety features
Advanced safety features in Nice
Casts (ClassCastException)
Null pointers (NullPointerException)
Writes to covariant arrays (ArrayStoreException)
Array index out of bounds (ArrayIndexOutOfBoundsException)
Comparison with functional languages

Introduction

Programming is a complex and error prone task. The most obvious consequence of this fact is the presence of bugs in programs. Every user can experience that, for most software, there are are ways to use it that lead to inappropriate results, internal error messages or even termination of the program, if not of the whole computer. A hidden consequence of bugs is a large amount amount of effort, time and money spent in tracking and solving them.

Some bugs are due to an error in the global conception of the program. These can only be solved -- or better, prevented -- by clever programmers using adequate design methods and appropriate testing. However, many bugs come from small mistakes. Every programmer will sometimes forget to initialize a variable, omit an argument to a function, ... The fact is that Man is capable of complex abstract thinking, but rather bad at checking small but numerous details. Luckily computers are precisely the opposite: poor at thinking, tremendously efficient at tedious tasks.

This observation naturally leads to our motto: that programming languages should rule out as many trivial errors from programs as possible. The programmer can then concentrate on higher level issues. The degree in which a language guarantees that a correct program will not fail at runtime is sometimes called static safety. All in all, this approach can lead to easier to create and more reliable software.

We shall first look at a few advances that have been made in the past in this direction. Then we will see how Nice improves on existing languages in this respect.

Existing safety features

Let us first distinguish different kinds of errors in a program, in decreasing order of severity:

Run Time Crashes

The program is abruptly terminated by the Operating System, or hangs the computer [1].

Run Time Error

An incorrect behavior is detected during the program execution. In the least, this allows for graceful termination of the program. Better, only some feature of the program is out of order, but the execution continues normally. This is the case in a language with exceptions, if the program catches the exception and is able to recover.

Compile Time Error

The compiler detects a problem, and refuses to generate the executable version of the program. The compiler should also locate and describe the error to ease the correction by the programmer.

The use of types prevents from mixing up numbers, strings, booleans, arrays and user-defined data.

All run time crashes can be converted to run time errors, which is unarguably an improvement of the safety. This typically involves checking at run time all possibly invalid code before executing it. An example is checking that an access to an array lies inside its bounds. These checks can either be inserted in the generated code, or done by an interpreter.

This is roughly the situation today for mainstream languages today. While it has improved since, say, the C programming language, there are still many run time errors that can occur. Now let us see how Nice can transform many of these run time errors into compile time errors, thus improving safety.

Advanced safety features in Nice

Java allow casts of the form: (T) e. At compile time, this assumes that the expression e has type T. At run time, if e does not evaluate to a value of type T, a ClassCastException is thrown. In this case, there is usually nothing that can be done to recover from the situation: the code that follows relies on the fact that e has indeed type T. Therefore ClassCastExceptions are usually not caught before the very top level of the program, making at least a whole feature to fail. It would be great to ensure that no cast can fail. Even better, not to have casts at all.

So why does Java allow casts? It needs them, because its type system is too limited. Nice has a powerful type system and no casts. So let us look at the different uses of casts in Java and their cast-free equivalent in Nice.

Collections

One of the limitations of Java is the absence of genericity: classes and methods cannot have type parameters. Casts are often a poor way to make up for this absence. Here is the example of a stack in Java:

interface Stack
{
  void push(Object element);
  Object pop();
}

Stack st = new StackImpl(); // we want a stack of strings
st.push("Element A");
st.push(new Object()); // invalid code, but not detected
...
String s = (String) st.pop(); // throws a ClassCastException

A few remarks on this Java code:

  • there is no way to specify that the stack should only contain strings;

  • this forces to cast every element pop'ed out of the stack;

  • the invalid push is not detected at compile time. Much worse, it will not even fail at runtime. On the contrary, the error occurs at the pop line, which is perfectly valid. It might require a good debugger and fair amount of time to track down where an invalid element was pushed on the stack.

Here here the equivalent in Nice, using a parameterized interface:

interface Stack<T>
{
  void push(T element);
  T pop();
}

Stack<String> st = new StackImpl();
st.push("Element A");
//st.push(new Object()); // type error
...
String s = st.pop(); // no cast needed

Nice is not the only alternative to Java with parameterized classes. See for instance GJ, which puts a strong emphasis on compatibility with Java. However we shall now move on to other features of Nice and that are not present in other languages, and that are give higher safety and power.

Multiple dispatch

In most object-oriented languages, methods are selected at run time depending on the class of the first argument. Because this first argument has such a distinct role, it is syntactically separated from the others, and place before the name of the method, before a dot. However, it is sometimes necessary to select a method depending on several arguments. Here is a typical example, defining the equals method for a user-defined class:

class Person
{
  String name;
  int age;

  boolean equals(Object that)
  {
    if (!(that instanceof Person))
      return false;

    return 
       name.equals(((Person) that).name)
       && age == ((Person) that).age;
  }
}

Ideally, we would only want to define the value of equals when both arguments are of this class. When it is not the case, we would rely on other code for deciding equality. This is possible using multiple dispatch [2], which is present in Nice. Here is the Nice code.

class Person
{
  String name;
  int age;

  boolean equals(Person that)
  {
    return 
       name.equals(that.name)
       && age == that.age;
  }
}

Instanceof

Casts are not always used to overcome limitations of the type system. They can also be used in conjunction with run time type testing to write code that depends on the class of a value. For instance, suppose we want to access the list of children of a GUI component, but not all components have a children property:

Component c = ...;

List children;
if (c instanceof ContainerComponent)
  children = ((ContainerComponent) c).getChildren();
else
  children = null;

There are two possibilities in Nice :

  1. create a method

    This is impossible in Java because methods can only be defined inside the class they deal with. Nice allows methods to be defined directly at the toplevel of a package. Thus we can define a children method that operates on all components, and that returns null if the argument is not a container:

    private ?List<Component> children(Component);
    
    children(Component c) = null;
    children(ContainerComponent c) = c.getChildren();
    

    We can now write our example with only:

    Component c = ...;
    
    ?List<Component> children = children(c);
    

    This is especially useful if this code occurs at many places. We shall now see the alternative, which matches very closely the Java version, and is practical if the code is rare.

  2. safe version of instanceof

    The idea here is simply that just after an instanceof test, the compiler can automatically adjust the type of the variable tested to take into account that the test succeeded. Therefore, the cast is completely useless; there is no reason to ask the programmer to write it. Therefore, it is perfectly legal in Nice to write:

    Component c = ...;
    
    ?List<Component> children;
    if (c instanceof ContainerComponent)
      children = c.getChildren();
    else
      children = null;
    

    In the first branch of the if test, c has type ContainerComponent. The compiler then checks that getChildren can be called safely.

Null pointers (NullPointerException)

In current imperative languages, references (or pointers) can hold a special value meaning "reference to nothing". This value is called null in Java, NULL in C and C++. At run time, however, dereferencing this value results to a runtime error (NullPointerException) or a run time crash (bus error, segmentation fault, protection fault, ...).

To prevent this error, a reference must be tested before use. However it is easy to forget to do so. Furthermore, there are references that are never null, or rather that should never be. Testing such references clutters the code. Every variable should therefore be documented as being possibly null or not. Every method should document whether each of its argument can be null or not, and whether it can return a null result. But then remains the task of checking that the code indeed is correct and indeed conforms to the documentation. Correctness requires for instance that if a variable is possibly null, it should always be tested before dereferencing. It also requires to match arguments of a method to its documented behavior regarding null arguments. All these checks are rather simple but very tedious. The situation is even much worse when code evolves: this checking must be done all over again.

Here obviously comes our motto: all this checking should be done automatically. This is exactly what Nice does. One documents whether a type can hold the null value by simply prefixing it with the ? symbol. Thus: ?String name; is the declaration of String variable that might be null. To get its length, one must write int len = (name == null) ? 0 : name.length();. Calling name.length() directly is a type error. It would only be possible if name was defined as String name = "Some non-null string";.

Writes to covariant arrays (ArrayStoreException)

In Java arrays are covariant: a String[] array can be passed to a method that expects an Object[] argument. But what happens if the method writes a Picture into the array? No error is detected at compile time. At run time, an ArrayStoreException is thrown.

This shows that arrays should not not be covariant. So why are they covariant in Java? Once again, mostly because of its limited type system. Object[] is often a poor replacement for T[] where T is a type parameter. Another reason is that covariant arrays are sometimes safe: when they are used in a read-only way.

In Nice, arrays are not covariant. Therefore run time errors like ArrayStoreException never occur. Moreover, it is still possible to use arrays covariantly while only reading from them. This requires Nice's powerful type system: constrained type parameters: <java.awt.Component T> void read(T[]); can be applied to arrays whose component types are subtypes of java.awt.Component. Type checking guarantees that the array will not be written to by this method, so that there will be no run time failure.

Array index out of bounds (ArrayIndexOutOfBoundsException)

A run time error occurs when a program tries to access an element from an array with an index outside its bounds. Solving this issue is still an open problem. Partial solutions exist, notably using dependent types, but they are not ready for widespread use because of their high complexity.

Nice offers a much simpler and limited contribution, but it can be very useful in practice. Code using arrays contains a few idiomatic patterns that occur repeatedly: iterating through the elements of an array, finding an element matching a certain criterion, ... These are typically done using loops. Besides being a little tedious, these patterns open the opportunity for mistakes in the indexes, which leads to run time errors. These errors will often be discovered soon while running the program, but it is still better if they can be detected by the compiler. And if they are seldom executed, and the indexes go out of bounds in rare circumstances, detection becomes more hazardous. Moreover, if a loop misses the incrementation step, it will loop forever, which gives no information on the location of the problem. It becomes then necessary to use a debugger and takes some time to spot what was but a minor mistake.

Using two features of Nice, genericity and higher order functions, it is possible to use and write functions that perform the most common tasks on arrays, and more generally collections. For instance, a simple iteration on the elements

for (int i = 0; i < a.length; i++)
  doSomething(a[i]);

can also be written in Nice

a.foreach(doSomething);

Using methods like foreach makes the code clearer by avoiding the repetition of the loop code over and over. Moreover, it removes the risks of wrong indexes, forgetting to increment the index, ... It is important to note that foreach is not a built-in operator but a normal method defined in the standard library. Therefore, given a user-defined data structure, a new looping function can be written and only has to be checked once.

Comparison with functional languages

We considered here imperative languages. There is another important family of languages that is worth considering: functional languages. More precisely, since we are interested in static safety, statically typed functional languages, the two major ones being ML and Haskell. These languages are doing very well as far as static safety is concerned. However, they achieve this safety by enforcing a quite different programming style. This makes it difficult to compare expressiveness, and definitely compromises their chances of becoming used widely.

Let us take the example of the null value. The approach of functional languages is to provide option types. Thus String option is the equivalent of ?String in Nice. However an expression of type String cannot be used where a String option is expected. It has to be explicitly injected into an option type with the Some constructor. Therefore, "A" has type String, and (Some "A") has type String option. This puts a burden on the programmer, and forces a very different approach onto the current practice. On the other hand, using Nice requires a minimal change: adding some question marks to possibly null types. The code itself can be kept unchanged. That is, provided it was correct!



[1] In a decent operating system a program should of course not be able to hang the computer.

[2] Multiple dispatch has other benefits that are not closely related to safety. In particular, it allows for the addition of methods to pre-existing classes. This is important to fully achieve modular programming.