Skip to main content

πŸ”₯ Top 20 Java Coding Standards vs Anti-Patterns — With Real Examples & Fixes!

πŸ”₯ Top 20 Java Coding Standards vs Anti-Patterns — With Real Examples & Fixes!

Welcome to a no-nonsense, funny, and deeply educational guide that’ll help you avoid bugs, write cleaner code, and ace interviews. Let’s roll! 🎯

🎯 1. Avoid Wildcard Imports (import.*)

✅ Best:

import java.util.List;
import java.util.ArrayList;

❌ Worst:

import java.util.*;

πŸ’₯ What goes wrong:
- Conflicting classes (like java.util.Date vs java.sql.Date)
- IDE slows down due to unnecessary type loading
- Harder for humans to read

πŸ˜‚ "I use * because I believe in surprises!" — Future you debugging a Date conflict


⚡ 2. Fail Fast Design

if (user == null) throw new IllegalArgumentException("User can't be null");
user.getName(); // Boom! NPE gift 🎁

🧠 Catch bugs early, easier to debug.


πŸ›‘️ 3. Immutable DTOs

public record UserDTO(String name, int age) {}
public class UserDTO {
  public String name;
  public int age;
}

πŸ“› Mutable objects = unexpected behavior in threads, REST, cache.


πŸ” 4. Avoid Infinite Loops Without Exit

while (!shutdownRequested) {
  processQueue();
}
while (true) {
  /* endless suffering */
}

πŸ’₯ CPU spikes, memory leaks, stuck services.


🧽 5. Avoid Empty Catch Blocks

try { doStuff(); } catch (IOException e) {
  log.error("IO failed", e);
}
try { doStuff(); } catch (Exception e) { }

🀐 Silent bugs = production chaos


🧠 6. Use Meaningful Variable Names

int retryAttempts = 3;
int x = 3;

πŸ˜‚ "x, y, z are for algebra, not billion-dollar apps."


🧯 7. Close Resources Using Try-With-Resources

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {}
BufferedReader br = new BufferedReader(new FileReader("file.txt"));

πŸ’£ Not closing = file handle leak.


πŸ”„ 8. Avoid Nested Ifs — Use Early Return

✅ Best (Early Return):

public void process(User user) {
    if (user == null) return;
    if (user.isBlocked()) return;

    sendWelcomeEmail(user);
}
  

❌ Worst (Nested Ifs):

public void process(User user) {
    if (user != null) {
        if (!user.isBlocked()) {
            sendWelcomeEmail(user);
        }
    }
}
  

πŸ’₯ Why it's bad: Adds unnecessary nesting, reduces readability, and makes debugging harder.

πŸ˜‚ "Every extra if block is like an extra door you must open while panicking during a fire." πŸ”₯πŸšͺπŸšͺπŸšͺ



🚫 9. Don’t Hardcode Values

final int MAX_USERS = 100;
if (users.size() > 100)

🧠 Use named constants = clarity and easy maintenance.


πŸ” 10. Avoid Repeated Code (DRY Principle)

sendEmail(user); sendEmail(admin);


Copy-pasting the same logic = future maintenance nightmare.
πŸ˜‚ "Ctrl+C, Ctrl+V = Ctrl+Alt+Screaming!"


πŸͺ“ 11. Don’t Use Magic Numbers

final int TIMEOUT = 5000;
Thread.sleep(5000);

πŸ’₯ Magic numbers = no context, harder to change.


πŸš₯ 12. Log Responsibly

log.debug("User found: {}", user);
System.out.println("User: " + user);

🚫 Don't leak passwords or PII in logs!


🧱 13. Avoid God Classes

Break into smaller focused classes (UserService, PaymentService)


1 class with 2000+ lines and 48 responsibilities = monster


πŸ” 14. Always Validate Inputs

Objects.requireNonNull(email, "Email can't be null");

Blindly trusting inputs = πŸ’£


⌛ 15. Use Final for Constants

final int PORT = 8080;

int port = 8080;

🧠 Use final to prevent accidental changes


🌐 16. Separate Concerns — No Logic in Controllers

Controller → Service → Repository
Mixing DB, business logic, logging in one class = 😫



πŸ”— 17. Override equals/hashCode Properly

Use IDE/Lombok
Writing equals() based on mutable fields = HashMap chaos


πŸ”„ 18. Don’t Modify Collections While Iterating

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  if (it.next().equals("bad")) it.remove();
}
for (String s : list) {
  if (s.equals("bad")) list.remove(s);
}

πŸ’₯ Will throw ConcurrentModificationException


πŸ§ͺ 19. Write Unit Tests

@Test
public void testOrderCreation() {
  assertEquals(2, orderService.create().size());
}

❌ "If it compiles, ship it" πŸ™ˆ


πŸ“œ 20. Document Your Code

/**
 * Validates login credentials
 */
// login stuff

🧠 Write WHY, not just WHAT



πŸŽ‰ Wrapping Up — Your Code, Your Story!

You've just gone through 20 powerful coding habits that can turn your Java from 😩 “Why is this breaking?!” to πŸ’ͺ “This code looks solid!”

🧠 Even small things like naming a variable userList instead of ul can make a huge difference.

πŸ’¬ Got a horror story from production? Or a funny naming disaster like List l = new List();? Drop it in the comments! Let’s laugh and learn together πŸ˜„

πŸ” I’ll keep turning my past mistakes and learnings into posts like this — so we all grow, fail less, and code smarter!

πŸ› ️ Until next time:
✔️ Think twice
✔️ Code once
❌ Never ignore that warning in your IDE! πŸ˜…

πŸ‘‹ Happy coding, and may your bugs be few and your logs always clear! 🐞✅

Comments

Popular posts from this blog

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too πŸ€”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” πŸ˜… Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model πŸ‘©‍πŸ’» Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections πŸ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside πŸšͺ ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

πŸ’‘ Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😡‍πŸ’« “Why is Redis cache not working?” 🀯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🀷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } πŸ•΅️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: πŸ›‚ Watchman = Spring Proxy 🏠 Your apartment = Your service class πŸšͺ Your room = A method inside that class πŸƒ Scenario 1: Outsider Visits Your friend from outside...

🧡 Virtual Threads in Java — The Ultimate Guide with Diagrams, Code & Interview Qs!

πŸš€ “How are Virtual Threads different from Thread Pools?” 😡 “Are they OS threads or JVM threads?” πŸ™ƒ “Should I still use CompletableFuture?” 🀯 “How do I even use them in real-time microservices?” 🧠 What are Virtual Threads? Virtual Threads (introduced in Java 21 as stable πŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel. πŸ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads. 🧠 What is the OS Kernel? πŸ›️ OS Kernel = The Brain of the Operating System It’s the core part of your OS (Windows, Linux, Mac) that: Manages memory 🧠 Schedules threads πŸ•’ Talks to hardware πŸ’» Handles I/O operations πŸ“¨ When you create a traditional thread in Java, the JVM asks the OS Kernel to create a real OS-level thread. πŸ–Ό️ Imagine This... ┌───────────────────────────┐ │ Your Java Application │ └────────────┬──────────────┘ │ ...