Talking about numbers

One of the most anticipated talks at Voxxed Days Athens 2017 was the one given by Mr. Douglas Crockford, who is best known for having invented JSON (JavaScript Object Notation). His talk was about the use of numbers throughout history, from the very beginning of mankind, until today, the era of information.

In particular, his talk raised awareness of the pitfalls of modern programming languages, which provide us the option to use more than one data types to represent numbers. This makes it error prone for developers, who may not be aware of which numeric data type may be the most suitable one for a given application, so as to prevent any overflows from happening.

For instance, Java provides several numeric data types, such as: int and long. If we used an int (32-bit) to add or multiply two numbers, we would be running the risk of an overflow, without ever knowing about it. To prevent an overflow, we should ideally be storing the result to an integer data type having more bits than int, as follows:

int (32-bit) + int (32-bit) => int (33-bit)

int (32-bit) * int (32-bit) => int (63-bit)

Concluding, the speaker urged us to create a new programming language, which must support only one numeric data type, namely the dec64, as documented here.

Working with numbers

As software developers, how can we ensure that we are safely using numbers in our applications? Should we embark on an adventure to implement a new programming language with dec64, as suggested above?

Personally, I believe that we shouldn’t worry about working with numbers in Java! Since Java 8, java.lang.Math has been enriched with the following new methods, which throw an ArithmeticException when the result overflows an int:

public static int addExact(int x, int y) throws ArithmeticException

public static int multiplyExact(int x, int y) throws ArithmeticException

Alternatively, we could be using java.Math.BigInteger to perform our arithmetic operations.

What do you think? Do you worry about working with numbers in Java? If you are one of the adventurous developers who will build their own programming language instead, please drop me a line :)