I was wondering the other day about the compatibility and style of my Java code. As of Java 14, the enhanced switch
has really become available. I have attached this below for comparison. 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. In my experience, few people that needed to run my code actually used a higher version than Java 8. Is there a general rule to determine on which language level code should be written?
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 } }
Advertisement
Answer
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 code base with far too much old fashioned clunky code; e.g. explicit boxing/unboxing, raw types, flaky resource cleanup in finally
blocks and so on. Ultimately your productivity suffers.
(And the corollary is that you need to make a judgment on how much benefit you will get in productivity and long term maintainability from each new language feature you are considering. Some will be less beneficial than others.)
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 …)