innoventes
Published in

innoventes

Var in java?

If you are like me who picked up java when it was released a quarter of a century back, chances are that you will appreciate this.

The backend for one of our projects is in java and spring boot. As part of best practices of software development, we configured our code to be analysed by Sonarqube, an awesome tool for code quality.

As we looked at the different types of issues reported by the tool, we spotted this one

Declare this local variable with “var” instead.

Hey, was I reading this right? This is java code and not javascript, right? Even in javascript, we now should be using let and const to scope the variables correctly. var in java? On clicking the Why is this an issue? link, we were presented with more details.

Quoting from the details displayed by Sonarqube

Local-Variable Type Inference should be used

In Java 10 Local-Variable Type Inference was introduced. It allows you to omit the expected type of a variable by declaring it with the var keyword.

While it is not always possible or cleaner to use this new way of declaring a variable, when the type on the left is the same as the one on the right in an assignment, using the var will result in a more concise code.

This rule reports an issue when the expected type of the variable is the same as the returned type of assigned expression.

Boy, weren’t we glad we decided to use Java 11, rather than Java 8 to build this application? As you can see above, this feature came into Java in Java 10.

So, instead of

AgentAPIResponseDTO agentAPIResponseDTO = agentMapper.getAgentAPIResponseDTO(agent);

we could do

var agentAPIResponseDTO = agentMapper.getAgentAPIResponseDTO(agent);

This is not the only thing that Sonarqube revealed. Another java language construct (from Java 8) is Optional. If you use recent versions of spring-boot, you will automatically use it (since the findById method returns an Optional)

Now how to initialize an Optional?

If you thought

Optional<Agent> existingAgentOp = null;

was valid, think again. While there is no compilation (or runtime) errors, Sonarqube tells you

Replace this null literal by an “Optional” object

Again, quoting from their explanation

The concept of Optional is that it will be used when null could cause errors. In a way, it replaces null, and when Optional is in use, there should never be a question of returning or receiving null from a call.

So the way to go would be

Optional<Agent> existingAgentOp = Optional.empty();

So, there it is! Something new learnt today!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store