Software developers everywhere have been very excited about the changes set to go in effect with the new JEP (Java Enhancement Proposal). However, before we talk about what lies ahead, let’s take a few steps back to revisit the expertise it takes to propose improvements in a programming language as strong and as dominant as Java. In this blog, we talk about the top Java developers who share their best coding practices

1. Error Management: How Good Are You?

Whether you figure among top software engineers or are an amateur Java Developer, you’ve doubtlessly encountered the infamous NullPointerException (NPE) at some point in your software development career.

Java Developers Working With NullPointerException

The problem is real with NPE, as developers either struggle to debug NullPointerException errors or are unable to locate them in the code. Unlike other errors, the NPE can’t be easily detected. The NullPointerException is basically a runtime exception in Java. It is generated when we try to use an object reference that has a null value assigned to it.

Null, as the name suggests, is the absence of any value. It is primarily used to show that there is no value assigned to a reference variable. It is used in a linked list to end the list. Now according to JDK documentation, NullPointerException pops up when the code tries to use an object reference that has a null value assigned to it. For example, calling a method from a null object or trying to access a null object’s field.

Pointers in Java?

Now here’s where it gets interesting: Java Developers, especially those just starting out, revert with: “But wait, why are we talking about pointers? There are no pointers in Java, right?”

Wrong.

Java has pointers but they are internalized. Pointers are used in Java to access objects. The developer has no access to declare a pointer directly or access it like in other programming languages. But the function is always the same: To point from one memory address to another.

How Elite Talent Deals With NPE

All IT Developers would obviously want to avoid the NullPointerException. Usually, this problem is addressed during the coding process itself—by making sure that all the objects are initialized properly.

When a reference variable is declared in memory, the coder (let’s say, the Java Coder) must first verify that the object is not null. He/she can only request a function or a field from the object following this verification. This routine minimizes the chances of NPE.

However, one still cannot eliminate errors from programming entirely. Even elite software engineers struggle with NullPointerException because as all this working is done internally, it is almost impossible to locate it manually.

Debugging each variable consumes a lot of time and makes the process very monotonous as well. JVM (Java Virtual Machine) has made it possible to point out the occurrence of the exception within the error. It points to the exact function and even the line of the code where the NPE originated. The following example illustrates the error:

Exception in thread "main" java.lang.NullPointerException
at Prog.main(Prog.java:5)

Although the error line is easily identified this issue isn’t entirely resolved.

Problems still exist in complex code, with multiple variables in a single line, each variable requiring debugging. Although it doesn’t sound very complicated, it is. The code’s author isn’t always responsible for debugging. Usually, a different team handles this task, and it isn’t easy for them to locate and fix NPE.

JEP 358: Helpful NullPointerException

Still struggling to complete your project with the error coming up again and again? You haven’t been alone. The top talent of the software industry came together to suggest a solution via the JEP (Java Enhancement Proposal) featured in the Java 14 JDK (Java Development Kit). JEP 358 was introduced by the leading talent of the industry, Lindemaier and Schmelter.

The solution they proposed focuses on bytecode instructions. By analyzing the bytecode instructions of the code, the JVM should be able to pinpoint the exact variable that returns a null value. The JVM output will be a message with all the details along with the NullPointerException. Something like this:

Exception in thread "main" java.lang.NullPointerException:
Cannot assign field 'a' because 'x' is null.
at Prog.main(Prog.java:5)

In case of more complex codes, it will point out all the instances, like this:

Exception in thread "main" java.lang.NullPointerException:
Cannot read field 'a' because 'x.y' is null.
at Prog.main(Prog.java:5)

A Solution To Make Java Development Jobs Easier

Can this thinking be used elsewhere in the software development process? Yes. By improving how they handle or fix NullPointerExceptions, programmers can also improve their approach to exceptions generated by the JVM. The authors of this JEP are now focusing on how to resolve the abrupt termination of programs.

This solution will also play a helpful role in improving the overall experience of Java Coders and testers by providing information that will be useful during troubleshooting and debugging. It will save a significant amount of time. Novice software developers and students will now be able to improve their understanding of NPE and coding in general. Debugging is, without a doubt, one of the best ways to understand code. The more the information that can be provided with errors, the more comprehensible the debugging process becomes.

2. Using New Developer Tools Efficiently—The Case For Hidden Classes

Hidden Classes in Java: Why the Hype?

Java coders or any developer for hire, for that matter, depends on industry progress for career progress. The more dynamic one’s chosen technology stream, the more software engineering job opportunities arise from technology recruiting as a whole. Such dynamism is also what keeps programming languages from fading into oblivion. New features are central to attracting top talent in the technology industry, JavaScript and Python are prime examples.

The Java Enhancement Proposal (JEP) is a process or methodology for collecting proposals from the top talent in the industry especially those elite software engineers who are working on Java or JVM languages. A helpful entry in the first JEP 2020 was the proposal of introducing hidden classes in Java.

Hidden Classes In Java-Why The Need?

Hidden classes are those classes that cannot be accessed by other classes or even by the developer. Hidden classes are automatically generated at run time and the developer can only create an object out of that class. As the name suggests, they are basically non-discoverable by users or any other class.

Limitations Of The Current Version

Normal classes are static. They are created during compilation right before execution of the code.

Java Developers who use frameworks know that a class created by a framework is dynamic but the Java APIs that create classes cannot differentiate whether the class was created dynamically at runtime or statically during compilation, since all classes are defined as “visible” by default. A class created by a framework must not be visible to the user or other class. The purpose is to guard it from alterations that may prove harmful for the program. Classes created by frameworks aren’t expected to have a long shelf life either.

Hidden Classes: Features That Help Software Developers

The main attribute of a hidden class is that it is invisible (and thus, inaccessible), making it the perfect framework-created class. The top technology talent within the Java community realizes the benefits this holds for them.

With hidden classes, frameworks can define classes that are different from static classes. They will be non-discoverable and will hide implementation details of the framework. It will become virtually impossible to link them with other classes.

With their increased liberty and support, frameworks will have the flexibility of defining as many non-discoverable classes as required, without getting caught up on aggressive unloading of non-discoverable classes.

The best part? The Java programming language stays as is, with no change whatsoever.

Many Java Virtual Machine (JVM) languages depend on dynamic class generation due to their efficiency and flexibility. The same holds true for Java itself.

The top talent in the Java Developer community responsible for implementing JVM languages usually prefers a dynamically generated class to be part of the implementation of an existing, statically generated class.

If the standard API that creates classes is able to define hidden classes that are not discoverable and only exist for a specific duration, Java frameworks that are currently generating classes dynamically can instead create hidden classes. This will surely improve the efficiency of all JVM languages and can create the best software development jobs, attracting top talent to work on Java or on JVM languages.

Again, Why The Hype?

Why the hype around hidden classes? Earlier features added into Java programming offered multiple options.

A big reason is that this feature already exists in JavaScript and plays a very significant role there.  JavaScript is a dynamic language which means that the type of data used is defined at the time of code execution, which takes up more time compared to static languages such as Java itself. Another issue is that the dynamic size of variables cannot be determined so the memory offsets cannot be stored beforehand, unlike static languages.

How Hidden Classes Are Created In Java

When an object is created, a hidden class is created automatically. In fact, first a class is created then an object from that class is created. When the code to create an object is executed, we first get a hidden class, then the object is created that is linked to that hidden class. Initially, the hidden class contains no information, because the object has no properties. Developers can only work with the object created and as the properties of the object will be set, the hidden class will be affiliated with the same properties by the framework.

3. Finding New Ways To Solve Problems: Pattern Matching In Java 14?

Java 14, or as it’s officially called, the Java Development Kit (JDK) 14 is now being released for general use. Everyone in the Java Developer Community seems very excited by its major updates, including the JDK flight recorder, event streaming and switch expressions. The one we focus on in this article is pattern matching.

Pattern Matching For Java Developers

Pattern matching is basically the checking and pinpointing of a specific sequence or pattern of data from raw data. This is not to be confused with pattern recognition, as the match has to be exactly the same in the case of pattern matching, whereas exactitude is not needed in the case of pattern recognition. Pattern matching is one of the most fundamental and important paradigms in several programming languages. There are many applications for pattern matching in computer science. High-level language compilers (like Java) make use of pattern matching in order to parse code to determine if it is syntactically correct.

Use With “InstanceOf” Operator

Pattern matching—as included in Java 14–is to be used with the “instanceof” operator. Pattern matching allows detection of common logic in the code. As a result, the code can be made shorter, less recurrent and simple to read and write. At some point, every Java Developer, has used the ‘instanceof’ operator in his/her code to compare a reference variable. If the result turns out to be true, the process follows by explicitly casting it to the type you compared it with, to access its members. At this point we can extract our variables before we apply any further processing specifics to that type.

Here is a sample code for understanding:

if (vehicle instanceof Land) {
Land car = (Land) vehicle;
car.sports();
// other car operations
} else if (vehicle instanceof Water) {
Water ship = (Water) vehicle;
ship.cruise();
 // other ship operations
}

In the code above, for every conditional block, we are testing the vehicle parameter to decide its type. But first we need to convert it via a cast, then we can declare a local variable. We can perform operations specific to this vehicle only after these steps are complete.

Although this method works well, and developers have been using it for a long time, the top software developers in the Java Developer Community proactively drew attention to the fact that this is a very repetitive process. Readability is also very poor which makes it tiresome to work with, especially when the type needs to be tested. The problem exacerbates if we add a new vehicle.

A new pattern variable with the ‘instanceof’ operator is introduced in Java 14 via JEP 305. If the instanceof condition turns out to be true, the pattern variable is automatically bound to the variable that was compared, thus eliminating the need for explicit casting to use its members. As a result, Java Coders can conditionally extract components from objects. It takes less time and is comparatively safer.

Here is the same code with the improved instanceof operator:

if (vehicle instanceof Land car) {

car.sports();

} else if (vehicle instanceof Water ship) {

ship.steam();

}

Now here in the first, “if block”, we are matching vehicle against the type pattern “land car”. First, we test the vehicle variable to see if it’s an instance of land. If it is true, it’ll be cast to our land type, and finally, we will assign the result to car.

One thing to understand here is that the variable names “car and ship” are not existing variables, they are declared pattern variables.  If we attempt to use either variable in another location, a compiler error will be displayed, because these variables are also only in scope and they will be assigned when the respective pattern match expressions returns true.

It is evident that this version of the code is much more concise and easier to understand. It has been simplified and is much more readable now that the explicit casting has been removed. However, the scope of the pattern variable is currently limited. We cannot access it in the else block.

If we do this, an error will be generated by the compiler as Pattern Matching has been released as a preview language. What this means for Java Developers in general is that even though this feature is ready to be used by developers, it can be changed in future Java releases. Any changes that are made will reflect the feature feedback provided by software developers.

Pattern matching is just one of many new features in the new Java release that save time and simplify code. They’ve been received with both relief and excitement by a community of top technology experts, eager to do more in development. If there had ever been speculation that Java was a dying language, those rumors have been put to rest.

Conclusion

What we’ve covered here scratches the surface, (and then some) on good Java Development practices. And while these are habits adopted by the most elite talent of the Java community, this is not an exhaustive list. For instance, we haven’t discussed unit testing here–a core aspect of the process that ensures your error handling approach is perfect. As our experts confirm, until we actually conduct unit-testing we will never really know how reliable our application is. We will address the importance of unit testing in subsequent posts, focusing on the role they play in reducing the dangerous latent defects that surface post deployment. Keep visiting this space!

Author

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.

Write A Comment