Skip to content

chaseofthejungle/java-clean-coding-guide

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 

Repository files navigation

Java Clean Coding Guide

Table of Contents

  1. Tip #1: Follow Naming Conventions
  2. Tip #2: Use Self-Documenting Variable Names
  3. Tip #3: Keep Methods to the Point
  4. Tip #4: Keep Classes to the Point
  5. Tip #5: Choose Constants for Non-Changing Values...
  6. Tip #6: ... and Use Enums with Constants
  7. Tip #7: Handle Exceptions
  8. Tip #8: Be Cautious of NullPointerException
  9. Tip #9: Utilize Streams Properly
  10. Tip #10: Utilize Dependency Injection (DI)
  11. Supplemental Resources


Self-documenting code is easy to understand simply by reading it. Its purpose becomes apparent without needing extensive commenting.

Not a Great Idea:

String n = "Billy";

Better Idea:

String firstName = "Billy";


Classes should follow the Single Responsibility Principle (SRP): that is to say, they should 'have one job'. This is important for a variery of reasons, such as improving readability for oneself and other developers and clarifying the code's purpose.

Not a Great Idea:

public class Bookstore {
  // Customer logic
  // Order logic
  // Book logic
  // ... other responsibility here...
}

Better Idea:

public class Customer {
  // Customer logic
}
  
public class Order {
  // Order logic
}
  
public class Book {
  // Book logic
}

By declaring constants instead of variables, it is clarified that a value is not to be updated. Furthermore, accidental changes to the data are prevented.

Not a Great Idea:

int guesses = 5; 

Better Idea:

public static final int MAX_GUESSES = 5;



NullPointerException is thrown when an uninitialized object is attempted to be accessed or modified.

Not a Great Idea:

String firstName = null;

if (firstName.equals("Bob"))

Better Idea:

String firstName = null;

if (StringUtils.isNotEmpty(firstName) && firstName.equals("Bob"))

Consider using equalsIgnoreCase() for conditional logic, if the value should be evaluated the same way regardless of lowercase or uppercase letter usage (e.g., if "Bob" and "bob" are to be handled the same way).




About

An overview of best practices for coding cleanly in Java.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published