Writing Java Code Safely and Smartly with Null-Safety Using JPlus #178910
Unanswered
nieuwmijnleven
asked this question in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Select Topic Area
Show & Tell
Body
Null-pointer exceptions are a common error in Java, causing inconvenience for many developers. Preventing null pointer exceptions in advance is important, but for developers who want to focus solely on logic, handling them can be tedious. Moreover, it’s not always easy to account for every scenario. Typically, static analysis tools are used to detect potential null pointer issues, but developers still have to find and fix the code themselves. JPlus reduces that burden. Let’s write null-safe Java code with JPlus.
1. Access the JPlus GitHub repository and download the IntelliJ plugin
https://github.com/nieuwmijnleven/JPlus
2. nstall the JPlus IntelliJ plugin
File > Settings > Plugin > ⚙️ > Install Plugin from Disk3. Open the example project in IntelliJ
File > New > Project from Version Controlhttps://github.com/nieuwmijnleven/JPlusExampleClonebutton4. Create a JPlus file for User.java in the Project View
5. Making Java code null-safe with JPlus
User.jplus
Opening the generated User.jplus file, you can see error messages in the Problems tab.
By default, JPlus assumes all reference types are non-nullable, which causes these errors. The problematic parts are where the constructors of the User and Address classes are called.
Making Java code null-safe with JPlus
(1) Assume the name field is required
User.jplus
(2) Assume the address field is nullable
The Problems tab shows:
Then only the constructor-related error for name remains.
Replace null with "No Name" because name field is required.
Now only one error remains:
(3) Assume city in Address is nullable
All nullability errors disappear. Save the file (Ctrl + S) to generate new User.java.
User.java made null-safe by JPlus
Run the program:
No NullPointerException occurs, but some outputs are null. Use the Elvis operator ?: to provide default values.
Edit getCity() in User.jplus:
Also, be sure to press Ctrl + S to save. This ensures that the new Java code is saved in User.java.
User.java made null-safe by JPlus
Run the program:
All null values are replaced with "No City"
Summary
With JPlus, you can easily enforce null-safety in Java code. JPlus fully supports Java syntax, making it accessible for Java developers. The final code is converted to Java, allowing developers to review it. JPlus is still in its early stages and needs support from the Java community. Even small, regular contributions will help complete this project. Your support can make a real impact.
Become a Sponsor via Github
Become a Sponsor via PayPal.me
Beta Was this translation helpful? Give feedback.
All reactions