10 best practices in Java

Alexandru Nastase
9 min readAug 1, 2022

--

Java is a reliable and time-tested language. However, even the most experienced developers make mistakes from time to time. In order to write code that is easy to read and maintain, it’s important to follow best practices.

This blog post will discuss some of the most common Java best practices, and explain why they are important. Keep in mind that not all of these guidelines will apply to every project — use your best judgement when deciding what is right for your codebase.

Don’t forget that this blog will only present you the overall idea for each practice, but it will not go in depth, so if you know to know more about any of these best practices…*cough cough*… Google is your friend!

(I will also post links for more details about each one)

Let’s get started!

1. Follow SOLID Principles

Ok, so basically these are some object-oriented design concepts relevant to software development, which everyone of us should AT LEAST consider taking care of.

SOLID acronym stands for -

  • Single Responsibility Principle (SRP)
  • Open Closed Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

Here is a website where you can get into details about them.

2. DRY& KISS

I just can’t stress enough how important these 2 are.
Long story short:

  • DRY = Don’t Repeat Yourself
  • KISS = Keep It Simple Stupid

DRY is a basic principle of software development aimed at reducing repetition of information. The DRY principle is stated as, “Every piece of knowledge or logic must have a single, unambiguous representation within a system.”

Divide your code and logic into smaller reusable units and use that code by calling it where you want. Don’t write lengthy methods, but divide logic and try to use the existing piece in your method.

KISS is a design principle which states that designs and/or systems should be as simple as possible. Wherever possible, complexity should be avoided in a system — as simplicity guarantees the greatest levels of user acceptance and interaction.

Each method should only solve one small problem (the S. from SOLID), not many use cases. If you have a lot of conditions in the method, break these out into smaller methods. It will not only be easier to read and maintain, but it can help find bugs a lot faster.

3. Use Proper Naming Conventions

A programmer is always said to write clean codes, where naming has to be appropriate so that for any other programmer it acts as an easy way out to read the code.
At a smaller level, this seems meaningless but think of the industrial level where it becomes necessary to write clean codes in order to save time for everyone who reads your code.

In java, it is good practice to name class, variables, and methods as what they are actually supposed to do instead of naming them randomly. These naming conventions must be followed while developing software in java for good maintenance and readability of code. Java uses CamelCase as a practice for writing names of methods, variables, classes, packages, and constants.

Here you can check more about them.

4. Stop Hardcoding Stuff

If you’re a programmer, there’s a good chance you’re guilty of hardcoding stuff. You know what I’m talking about — it’s when you put literal values into your code instead of using variables. For example, let’s say you’re writing a program to calculate someone’s age. If you hardcode the current year into the program, then every time someone runs the program, they’ll get the same age. But if you use a variable for the current year, then the age will be calculated correctly every time.

Hardcoding values into your code is generally considered to be bad practice, for a few reasons. First of all, it can make your code more difficult to read and understand. Secondly, it can make your code less reusable — if you ever need to use the same piece of code with different values, you’ll have to go in and manually change the hardcoded values. And finally, it can lead to errors if the values you hardcode into your code happen to change (for example, if the current year changes).

So next time you’re tempted to hardcode something into your code, think twice! It’s usually better to use variables instead.

5. Comment Your Code

When it comes to programming, there are a few universal truths that everyone must accept. First, there is no such thing as perfect code. Second, any given line of code will eventually need to be changed or deleted. And third, commenting your code is always a good idea.

When you come back to a piece of code that you wrote six months ago, chances are you won’t remember what it does or how it works. But if you take the time to leave a clear and concise comment, you’ll save yourself a lot of headaches later on.

In addition, commenting your code makes it easier for others to understand and work with. If you’re working on a team project, chances are that not everyone will be as familiar with the code as you are. By leaving comments, you can help others make sense of the code and avoid making mistakes.

So next time you’re programming, remember to take a few minutes to comment your code. It may not seem like a big deal at the time, but it can really save you a lot of trouble later on.

6. Declare Class Members Private Wherever Possible

Rule of thumb is to try to hide information as much as possible, sharing it only when absolutely necessary.

The idea is that only the class can access its private variables, so no other classes elsewhere in your code can interfere and mess something up by changing the private variables in unexpected ways. Writing code like this, with a bunch of autonomous classes interacting through a small number of strictly controlled public methods, seems to be an easier way to code.

Another advantage is related to the concept of ‘coupling’. A public member m of a class A that is used by another class B introduces a dependency: if you change m in A, you also have to check usages of m in B. Worse yet, nothing in class A tells you where m is being used, so again you have to search through the entire codebase

So, as to when you should make things private: I’d say make everything private by default, and then expose only those parts that absolutely have to be public. The more you can make private, the better.

7. Use StringBuilder/Buffer For String Manipulation

The main difference between StringBuilder/Buffer Objects and simple String ones, is that String object are immutable, but String Buffer/Builder objects are Mutable.

Now there is a concept of String Constant Pool. Every time u define a String object ,some memory is assigned for it in string constant pool. Now every time you modify this Object, new memory is allocated for every modified string. This unnecessarily wastes the memory.

Opposite is the case with Buffer and Builder Objects. The memory is allocated only once for the Object. Buffer and Builder objects are allocated memory in HEAP. Every time you modify the string the variable gets modified. So memory is not wasted.

Here you can find out more about the differences between String, StringBuilder and StringBuffer.

8. Learn To Check for Nulls

Generally, null variables, references and collections are tricky to handle in Java code. They are not only hard to identify but also complex to deal with.

As a matter of fact, any miss in dealing with null cannot be identified at compile time and results in a NullPointerException at runtime.

There are many ways in which you can check for nulls and actually avoid or take care of them. Itır Ege Değer, for example, has a great article about it.
Some of the methods she is mentioning are:

1. java.util.Optional
2. Utility classes of apache.commons
3. Objects::nonNull in Streams
4. requireNonNull methods of java.util.Objects
5. Lombok’s Builder.Default
6. NotNull, NotEmpty, NotBlank Annotations

You can read everything in details, along with code examples, here.

9. Use Design Patterns

If you’re a programmer, chances are you’ve heard of design patterns. For those who haven’t, design patterns are basically reusable solutions to common programming problems.

Sounds pretty useful, right? And they are!

Design patterns can save you a lot of time and effort when it comes to coding. But that’s not all they’re good for. Design patterns can also make your code more readable and maintainable. And they can help you to avoid common coding pitfalls. So if you’re not using design patterns, you should definitely consider doing so. They could just be the thing that takes your code to the next level.

There are a lot of design pattern out there, but I would personally recommend you to focus on reading about them (at least about the more popular ones), and understand the reasoning behind them.

Instead of memorizing all of them like a robot, try to actually SEE them being used. Try to recognize a design pattern when you see it. You need to look at a bunch of code and go like “ohh, I seee, so the builder pattern is used here…”

There is tons of information about design patterns. I will just post a link where I learned about them, so you can learn too!

Check them out here!

10. Your Code Is Like A Story

No matter how elegantly written, how efficient or how complex your code is, a piece of code is not going to make any sense unless it is well-organized and easy to follow.

That’s why the best code tells a clear, concise story that can be easily understood by anyone who reads it. In other words, your code should be like a good children’s book: each line should be expressive and contribute to the overall narrative. Of course, this doesn’t mean that your code should be boring or simplistic. On the contrary, the best code is often creative and expressive. But above all, it should be easy to read and understand. So the next time you sit down to write some code, remember: If you can’t explain it simply, you don’t understand it well enough.

Conclusion

It’s important to realize that the coding techniques you learn should not be applied blindly, without thinking. That is, while a practice can indeed be applicable most of the time, there are very few rules which should absolutely never be broken. Rules are blind, in the sense that they often don’t deal with the full context of a problem, or the complete picture.

You shouldn’t be afraid to consider breaking the rules, if you have thought about the problem, and when you feel it’s an appropriate thing to do.

When you begin your career as a programmer, following a standard set of rules is likely appropriate. But as you progress, your skills become stronger, and you start to develop something which is lacking in the beginner — a sense of taste. This sense of taste, this wisdom which you’ve acquired through real experience, is what really guides a mature programmer. In essence, wisdom transcends rules.

━━━━━━━━━━━━━━━━▼━━━━━━━━━━━━━━━━

My articles:

The struggle of getting my first job as a software developer
Will Java still be worth in 2023? ☕
The BLUB Paradox
Things I wish I knew as a beginner programmer

--

--

Alexandru Nastase

Java guy. Life newbie. Maybe smart maybe funny. Personal stuff here, too. WELCOME ! ❤