A fluent API for manipulation of distances in Java



Frameworks and tools




Back in 2017, I worked on the development of a routing engine at Praxedo. When working on a routing engine, you mainly deal with times and distances. Java 8 introduced a great Time API to allow clients to manipulate and operate with times. However, there is not such thing for the manipulation of distances, so I made Distance4J taking inspiration from the Java Time Duration API and adapting it to distance and length units.

Distance4J is a lightweight Java library that provides an easy way to convert and apply arithmetic operations on distance measures. The main purpose of Distance4J is to prevent common errors and annoying boilerplate when manipulating distances in different length units. With Distance4J, the consumer of a distance is unit-agnostic. Each client can choose the length unit to use, without needing to adapt to the unit in which the distance is provided with cunbersome conversions.

Instead of modelising a distance with a primitive magnitude with some implicit unit that is documented somewhere in the project, Distance4J provides a unit-agnostic model.

A distance can be created with any of the available factory methods:

Distance myDistance = Distance.of(12, LengthUnits.ImperialUS.YARD);
Distance anotherDistance = Distance.ofMetres(10.15);

Once a distance is instantiated, the client can manipulate it without needing any knowledge on the unit that the provider used for the initial measure. The client can manipulate the distance using the units it needs.

Distance addition = myDistance.plus(50, LengthUnits.SI.DECIMETRE);
Distance subtraction = myDistance.minus(anotherDistance);

Finally, when the client is done with the distance manipulation, the holded value can be retrieved in any unit:

double feet = myDistance.to(LengthUnits.ImperialUS.FOOT);
double metres = myDistance.toMetres();