Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most performant way to achieve type safety on primitive types in Java?

Let's say I'd like to ensure type safety in Java on primitive types. For the sake of an example, let us want to distinguish a Ratio from an AbsoluteValue, both are represented by a double.

Java to my best knowledge does not support type synonyms.

So I'm quite confident some overhead will be involved.

From the top of my head I could think of either defining new calsses which wrap double (a lot of boilerplate), or subclassing Double... or maybe there are even other options?

Which approach gives me the least performance overhead?

EDIT: I'm confined to Java 8, so that's the implicit basis of the question; however, if there are alternative solutions in newer versions of the language I'd still be keen to hear about them.

like image 883
A Sz Avatar asked Oct 30 '19 09:10

A Sz


2 Answers

The most performant way I can think of would be to write your own wrapper classes which have some marker annotation:

@PrimitiveTypeAlias(double.class)
public class Milliseconds
{
    double value() { ... } 
}

Then hook into the annotation processor at compile-time and physically replace the wrapper classes with their primitive counterparts (using something like Lombok).

... But I suspect you may have been implying "most performant and also low-effort" :)

like image 75
Michael Avatar answered Sep 25 '22 03:09

Michael


Take a look a Manifold framework (like Lombok but more concerned with Types than boilerplate reduction). @Extension methods or @Structural interfaces provide various ways of implementing "duck typing" which covers some of the requirement. It won't work directly with primitive fields though. A very basic wrapper class may be optimised by the JIT in various cases (and will be able to use Project Valhalla's inline modifier when that lands).

(I suspect it is a reasonable feature-request to implement first-class aliases to complement Manifold's existing feature set.)

like image 41
drekbour Avatar answered Sep 23 '22 03:09

drekbour