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