Java Quick Fixes

Sivaram Rasathurai
Javarevisited
Published in
5 min readFeb 22, 2023

--

Photo by Ekaterina Shevchenko on Unsplash

Java programming is like a box of chocolates — you never know what you’re gonna get!

But if you’re not careful, you might end up with a big mess of melted chocolate all over your code.

In this Blog, we’ll explore some of the most common Java coding mistakes and provide practical fixes that can help you avoid the chocolatey disaster and write better, cleaner, and more maintainable code.

1. Modifying a collection while iterating over it

Photo by Eran Menashri on Unsplash

Common Mistake: Modifying a collection (such as a List or Set) while iterating over it can lead to unpredictable behaviour and errors. This can result in a ConcurrentModificationException being thrown at runtime.

Quick Fix: Use an iterator or enhanced for loop to iterate over a collection, and use the iterator’s remove() method to remove elements from the collection.

List<String> myList = new ArrayList<>();
myList.add("foo");
myList.add("bar");
Iterator<String> iterator = myList.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("bar")) {
iterator.remove(); // Use the iterator's remove() method to remove the element
}
}

2. + Operator is used to concatenate String values

Photo by Crissy Jarvis on Unsplash

Common Mistake: Concatenating strings using the + operator can be slow and inefficient, especially if you’re doing it in a loop or with a large number of strings.

Quick Fix: Use a StringBuilder or StringBuffer to concatenate strings, which is faster and more efficient.

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("world!");
String result = sb.toString();

3. Using the wrong type of loop for the job

Photo by Jon Tyson on Unsplash

Common Mistake: Using a for loop when a while loop would be more appropriate, or vice versa.

Quick Fix: Choose the loop that best fits the task at hand. Use a for loop when you know the number of iterations in advance, and use a while loop when the number of iterations is unknown.

// Using a for loop to iterate over an array
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

// Using a while loop to read lines of input from a BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null) {
// Do something with the input
}

4. Using magic Numbers and String

Photo by Rhett Wesley on Unsplash

Common Mistake: Using the hard-coded values without proper meaning will make the code looks magic.

Quick Fix: Magic numbers and strings can make your code harder to read and understand, and can lead to errors when they are changed so Avoid using magic numbers and strings in your code, and use constants or enums instead.

//Mistake

if (status == 1) {
// Do something
}

if (type.equals("car")) {
// Do something
}

//Fix

public static final int STATUS_NEW = 1;

if (status == STATUS_NEW) {
// Do something
}

public enum VehicleType {
CAR,
TRUCK,
MOTORCYCLE
}

if (type == VehicleType.CAR) {
// Do something
}

5. Use exception handling properly:

Photo by Bermix Studio on Unsplash

Common Mistake: Catch all exceptions by exception class.

Quick Fix: Proper use of exception handling can make your code more robust and resilient to errors, and can make it easier to diagnose and fix problems when they occur. hence use exception handling properly by handling exceptions at the appropriate level and logging meaningful error messages

//Mistake
try {
// Do something that may throw an exception
} catch (Exception e) {
e.printStackTrace();
}
//Fix
try {
// Do something that may throw an exception
} catch (FileNotFoundException e) {
logger.error("File not found: " + e.getMessage());
} catch (IOException e) {
logger.error("IO error: " + e.getMessage());
} catch (Exception e) {
logger.error("Unexpected error: " + e.getMessage());
}

6. Methods are long or complexity

Photo by Alexis Fauvet on Unsplash

Common Mistake: Write all the logic into one code block and make it a method.

Quick Fix: Short methods are easier to read, understand, and maintain, and make it easier to isolate and fix bugs. hence keep methods short and simple, and aim for a maximum of 10–20 lines of code.

//mistake
public void processOrders(List<Order> orders) {
for (Order order : orders) {
if (order.getStatus() == OrderStatus.NEW) {
order.setStatus(OrderStatus.PROCESSING);
for (OrderItem item : order.getItems()) {
Product product = getProduct(item.getProductId());
if (product != null && product.getStock() >= item.getQuantity()) {
product.setStock(product.getStock() - item.getQuantity());
updateProduct(product);
} else {
order.setStatus(OrderStatus.ERROR);
}
}
updateOrder(order);
}
}
}

//fix
public void processOrders(List<Order> orders) {
for (Order order : orders) {
if (order.getStatus() == OrderStatus.NEW) {
processOrder(order);
}
}
}

private void processOrder(Order order) {
order.setStatus(OrderStatus.PROCESSING);
for (OrderItem item : order.getItems()) {
Product product = getProduct(item.getProductId());
if (product != null && product.getStock() >= item.getQuantity()) {
product.setStock(product.getStock() - item.getQuantity());
updateProduct(product);
} else {
order.setStatus(OrderStatus.ERROR);
}
}
updateOrder(order);
}

7. Overusing inheritance

Photo by Josue Michel on Unsplash

Common Mistake: Overusing inheritance can lead to tightly-coupled code that is difficult to maintain and modify. Using composition instead of inheritance when appropriate is the fix because it can result in more flexible and reusable code

Quick Fix: Use composition instead of inheritance when appropriate

8. Using the diamond operator to simplify generic type declarations

Common Mistake: Not using the diamond operator to simplify generic type declarations can result in verbose and error-prone code.

// Not using the diamond operator
List<String> words = new ArrayList<String>();

// Using the diamond operator
List<String> words = new ArrayList<>();

So there you have it, folks. We’ve covered some of the most common Java coding mistakes but this is just the tip of the iceberg. Java is a vast and ever-changing ecosystem, and there’s always more to learn and explore. So don’t stop here.

Keep practising, keep experimenting, and keep having fun. With the right mindset and the right tools, you can write Java code that’s not only bug-free but also elegant and enjoyable to work with. Thanks for reading, and happy coding!

--

--