10 common mistakes made by Java junior software developer and.. how to avoid them

By November 1, 2020

In this new article, we will expose 10 of the most frequent errors among Java developers. We will take this opportunity to discuss a way to detect them and thus offer our juniors a way to progress.

We were all young developers.

Young coders are fantastic, they can both shake our known stable and comfortable world with a new view of programming and at the same time be a source of renewed boredom and annoyance.

As we want to improve the overall quality of the code produced in our teams, it is important to train our developers well and share best practices. So at Embold, we capitalize on best practices to make our Junior Java coders, true java rock stars.

Let’s take a look together at the classic mistakes made by Java developers.

Naming: Bad variable and function names

Names are everywhere in software. We name our variables, our functions, our arguments, classes, and packages. Names should have a meaning and use the business dictionary terms (Ubiquitous Language is the term by Eric Evans.) Our TOP 1 mistake is also an important chapter of the Cleancode book from Robert Martin (cheat-sheet there).

This example can be improved :


public boolean isPNumber( String p) {
Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
return pattern.matcher(p).matches();
}

And now :


Pattern PNUMBER_INTERNATIONAL_PATTERN = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
public boolean isValidPhoneNumber(String phoneNumber) {
return PNUMBER_INTERNATIONAL_PATTERN.matcher(phoneNumber).matches();
}

Exception management

Ugly Exception Management code Ugly Exception Management code\

Java Exceptions are probably the most boring part of the Java programming language with the wildcards. Checked exceptions are often misinterpreted by inexperienced Java programmers and their treatment left blank.

The following figure illustrates the most frequent errors made when we are talking about exception management. We have nearly 40 % of our coders who are either skipping the catch blocks in their code (source GitHub) or printing the stack-trace using printStackTrace() method. It is absolutely scary.

Exceptions have been designed as a remedy to the coders that were ignoring the error codes returned in C/C++ like with fopen, malloc... Undoubtedly our coders still hate to handle error cases in Java

So please, let’s have a look at our excellent article about Exception Management and how Embold can help you to track these errors and get your code cleaner.

Monolithic methods

Often inexperienced coders write their code in a single shot. Clean code and better than average code require several steps of refactoring, testing ( in a continuous way aka TDD). Thus writing a single monolithic function instead of several sub-functions across different classes is not something rare among Junior coders.

Example : long method code Example: long method code\

On our example extracted from Embold, we see that this method shows several issues highlighted with the small colored markers. An easy way to spot a too long method is the presence of comments. Our comments convert to pdf, create a new document with the associated code make nice extracted single methods. The big plus, these methods are easier to test too with a decreased complexity.

Poor OOP Practices

Object-oriented programming and design patterns are something either ignored in some computer science degrees or too theoretical. I believe design patterns should be learned on practical katas ( code exercises ) with incremental improvements. It takes time and the right decision to use Object-oriented programming properly. To some extent, the same thought can be applied to Reactive Programming and Functional/Immutability programming too. Both are fascinating domains with a lot of practitioners, advocates, and coaches. It is impossible to know everything at first, that is why there are tools like Embold to track OOP issues and teach about better design :

Poor OOP practices Poor OOP practices\

 

 

Here are some rules easy to follow :

  • Lack of encapsulation: Making all properties public with getters and setters  ( anemic model ) is just breaking OOP principles
  • Coupling issues:  strong dependencies between some components make the design fragile or not testable.
  • Lack of abstraction: a lot of classes depends on other classes, interfaces and delegation is not used
  • Inheritance of hell: your class extends a tree of classes that make blush Yggdrasil itself.

Poor OOP practices Poor OOP practices\

Not Paying Much Attention To Readable Code

One spooky habit of the young coder is to show his ability for fast coding. As Fowler quoted “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” Therefore the code should be easy to be read. A first skill to obtain is to understand the link between Code Complexity, the presence of bugs, and testability. This skill will help you to identify complex code and provide a sense of danger while watching some code :-) Once you will learn how to do automatic testing, you will understand how painful are complex codes.

Readability code Readability code\

Another important way to obtain a code easy to read is to avoid copy past ( see also our Monolithic method hint) and learn how to refactor duplicated code. When you are extracting your code, provides also meaningful names. The code should be such that one should be able to understand it even after returning to it after some time gap, without that person having to look at every line of it

Code cannot be tested ( and probably is not tested too)

Testing a code sounds like an activity terribly unfriendly for young developers. Inexperienced coders do not know TDD, the benefits to write code that can be tested. Your code should conform to the FIRST principle.

Agile in a Flash: F.I.R.S.T Agile in a Flash: F.I.R.S.T\

 

Test Hungry code example Test Hungry code example\

After some years of experience, the common testing practices (RED/GREEN, BDD, TDD) becomes important tools of an experienced coder.

Knowing how to write tests; good tests and design your code to write efficient tests is a vital thing. It helps you to write better code, readable code, and that match your customer’s needs.

Test Hungry code example Test Hungry code example\

 

Memory Leaks

Memory leaks are a tricky production issue totally unknown by young programmers. Memory is finite and under certain circumstances, the code may reach the maximum of the server capacities. These issues are usually difficult to spot in a large messy base of code. Profilers and instrumenting tools are good to fix these issues but it requires a non-negligible training time.

Static code and methods everywhere Static code and methods everywhere\

Luckily, it exists some simple coding rules to follow to avoid future headaches :

Track for the inappropriate usage of static: memory leaks appear with container objects ( map, list, collections, arrays)  that are never emptied or with the useless object still stored. Static containers are most likely never destroyed.

Memory leak issues Memory leak issues\

Always think about the potential quantity of elements, a container will store: if your contains is receiving some records from a table, think about how many records are stored in this table? How many items will I receive from the network? Should I limit the number of items received? The paging pattern is a good way to limit the number of entries in your containers.

Provides a life-cycle policy: a good practice as it seems is to encapsulate your containers into Objects that are responsible for your object’s life. The container is inaccessible from the outside and requires to use of appropriate business methods ( add, delete). The container will ensure to delete the data when it is destroyed.

Poor null expression management

NullPointerException, lack of input data validation, lack of tests, all the causes are linked to a lack of reliability. Luckily Java applications do not crash like C/C++ applications otherwise our servers would stop every minute. Just check the stats below of running production servers. That is the main cause of fault in the Java servers. Luckily, static analysis tools are the best way (with code reviews ) to detect and fix these issues.

The Top 10 Exception Types in Production Java Applications - Based on 1B Events - OverOps

I recommend the following rules to immediately increase your code quality :

  • Never use NULL when you can use the empty notion of the type. A string can be empty rather than null, a number should never be empty, Boolean could take a default false value, a returned container should be empty rather than null.
  • Do not pass null as an argument. If a method allows a null parameter, it means you can declare two methods, one without the nullable parameter.
  • Replace the Null value returned by your method by the java.util.Optional return type.
  • When you need to express nullability in your API, uses the javax.annotation package and the @Nullable, @NotNull annotations
  • Last but not least uses static analyzers both in your IDE (IntelliJ IDEA) and your CI/CD (Embold)

Null pointer management issues Null pointer management issues\

 

Not closing resources

Resources should be closed after usage, temporary resources deleted and memory freed. These are the basic rules all developers should follow. However with the Java language; this is something often bypassed. The consequences are often invisible until the software reaches production. The server resources will be exhausted and a periodic restart necessary.

The rule is simple to follow :

  • Components that implements the Closeable interface must be freed after their usage (in the finally block)
  • Autocloseable resources should be used inside a try (resource) catch statement.
  • Custom components that implement a life-cycle should implement AutoCloseable.

 

Clsose resource issue Close resource issue\

Conclusion

In our quite exhaustive post, we reviewed the 9 common mistakes made by young Java programmers. And since we promised a TOP 10 list, here is our last one :

Be open-minded, do not be afraid to ask questions, and to receive honest feedback, programming is fun!