Home > Software design >  Java: style compability tradeoff
Java: style compability tradeoff

Time:04-05

I was wondering the other day about the compatibility and style of my Java code. As of JDK 14, the new switch architecture has really become available. I have attached this below for comparison. But now I find it questionable if you should really use this good style, because you would have to compile in Java version 14 in this case. Would you recommend me to use the old swich architecture so that I can compile into the widely used Java 8, or should I use the new architecture for less compatibility?

int a = 42;

// Old switch
switch(a) {
case 42:
    // Do something
    break;
default:
    // Do something else
}

// New enhanced switch
switch (a) {
    case 42 -> {
        // Do something
    }
    default -> {
        // Do something else
    }
}

CodePudding user response:

You are correct that the new switch statement and expression syntax won't work on older versions of Java. So that means that you need to consider whether you need your code to compile and run on older versions of Java.

But this is not a new problem. For example in Java 5, they introduced a number of new Java language constructs including generics, annotations, autoboxing and so on. And Java 7 introduced try with resources. And Java 8 introduced lambda expressions. Java is evolving.

It is up to each programmer / project to decide when to start using new language features ... according to their specific requirements and constraints. We can't really advise you because we don't know what your requirements and constraints are.

But if you take too long to switch to using newer language features, you might end up with an old codebase full of explicit boxing/unboxing, raw types, flakey resource cleanup and so on. Your productivity suffers.


When it comes to compilation, I'm more concerned with consumers who may only have a low version of Java installed ...

The flipside is that there are additional costs >to you< in supporting customers who can't or (more likely) don't want to upgrade to a more recent Java platform. At a certain point, it is best for everyone if you declare old versions of Java to be "no longer supported" for your product. (But we can't tell you when to do that. There are too many unquantifiable variables ...)

  • Related