Apps/Gaming

Java Best Practices

In computer programming, best practices are a set of informal rules that many developers follow to improve software quality, readability, and maintainability. Best practices are especially beneficial where an application remains in use for long periods of time, so that it was initially developed by one team and then subsequently maintained by a different group of people.

the Working with Java Variables article presented a number of best practices for variable naming. This series will now go much further and cover such topics as class member scoping, try/catch blocks, and even the formatting of constant values. This first installment will provide an overview of the best practices for Java that we will be exploring over the next several weeks, along with an explanation of the first three items in the top best practices for Java programming list.

Java Programming Best Practices at a Glance

Although the complete list of Java Best Practices can be a lengthy one, there are several which are considered to be a good starting place for coders who are taking their first steps into improving their code quality, including using proper naming conventions, make class members private , avoiding the use of empty catch blocks, avoiding memory leaks, and properly commenting code blocks:

  • Use proper naming conventions
  • Class Members Should be Private
  • Use underscores in lengthy numeric literals
  • Avoid empty catch block
  • Use StringBuilder or StringBuffer for String Concatenation
  • Avoid redundant initializations
  • Using enhanced for loops instead of for loops with a counter
  • Proper handling of null pointer exceptions
  • float or doubles: which is the right choice?
  • Use of single quotes and double quotes
  • Avoiding memory leaks
  • Return Empty Collections instead of returning Zero elements
  • Efficient use of thongs
  • Unnecessary Objects Creation
  • Proper commenting

Class Members in Java Should be Private

In Java, the more inaccessible the members of a class are, the better! The first step is to use the private access modifier. The goal is to foster ideal encapsulation, which is one of the fundamental concepts of object-oriented programming (OOP). All-too-often, new developers fail to properly assign access modifiers to the classes or prefer to keep them public to make things easier.

Consider this class where fields are made public:

public class BandMember { public String name; public String instruments; }

Class encapsulation is compromised here as anyone can change these values ​​directly like so:

BandMember billy = new BandMember();
billy.name = “George”; billy.instrument = “drums”;

Using private access modifier with class members keeps the fields hidden preventing a user from changing the data except via setter methods:

public class BandMember { private String name; private string instruments; public void setName(String name) {
this.name = name; } public void setInstrument(String instrument) this.instrument = instrument; } }

setters are also the ideal place to put validation code and/or housekeeping tasks such as incrementing a counter.

You can learn more about access modifiers in our tutorial: Overview of Java Modifiers.

We also have a great tutorial covering the concept of Java Encapsulation if you need a refresher.

Use underscores in lengthy numeric literals

Thanks to a Java 7 update, developers can now write lengthy numeric literals that have increased readability by including underscores (_). Here are some lengthy numeric literals before underscores were permitted:

int minUploadSize = 05437326; long debitBalance = 5000000000000000L; float pi = 3.141592653589F;

I think you will agree that underscores make the values ​​more readable:

int minUploadSize = 05_437_326; long debitBalance = 5_000_000_000_000_000L; float pi = 3.141_592_653_589F;

Avoid Empty Catch Blocks

It is a very bad habit to leave catch blocks empty, for two reasons: it can either cause the program to silently fail, or continue along as if nothing happened. Both of these outcomes can make debugging significantly harder.

Consider the following program which calculates sum of two numbers from command-line arguments:

public class Sum { public static void main(String[] args) { int a = 0; int b = 0; try { a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { } int sum = a + b; System.out.println(a + ” + ” + b + ” = ” + sum); } }

Java’s parseInt() method throws a NumberFormatExceptionrequiring the developer to surround its invocation within a try/catch block. Unfortunately, this particular developer chose to ignore thrown exceptions! As a result, passing in an invalid argument, such as “45y” will cause the associated variable to be populated with the default for its type, which is 0 for on internal:

Generally, when catching an exception, programmers should take one or more of the following three actions:

  1. At the very least, inform the user about the exception, either get them to re-enter the invalid value or let them know that the program must abort prematurely.
  2. Log the exception using JDK logging or Log4J.
  3. Wrap and re-throw the exception as a new, more application-specific, exception.

Here is our Sum application rewritten to inform the user that an input was invalid and that the program will be aborting as a result:

public class Sum { public static void main(String[] args) { int a = 0; int b = 0; try { a = Integer.parseInt(args[0]); } catch (NumberFormatException ex) { System.out.println(args[0] + ” is not a number. Aborting…”); return; } try { b = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { System.out.println(args[1] + ” is not a number. Aborting…”); return; } int sum = a + b; System.out.println(a + ” + ” + b + ” = ” + sum); } }

We can observe the results below:

Java error handling

Final Thoughts on Java Best Practices

In this first installation of the Java Best Practices series, we learned about the top 15 Java best practices and explored class member encapsulation, the use of underscores in lengthy numeric literals, and avoiding empty catch blocks. Next week, we will be looking at thong concatenation done right, how to avoid redundant initializations, as well as using enhanced for loops.

Reading: Top Online Java Training Courses and Bundles

Related posts

Top visualizations for game telemetry data

TechLifely

2023 will be the year of hybrid monetization

TechLifely

A simple introduction to using MySQL on the Linux terminal

TechLifely

Leave a Comment