Best Practices
## Learning Objectives
- Write clean, maintainable Java
- Follow naming conventions
- Master debugging
- Apply effective testing
## Code Style
### Naming Conventions
```java
// Classes: PascalCase
public class BankAccount { }
// Variables and methods: camelCase
int accountBalance;
void calculateInterest() { }
// Constants: UPPER_SNAKE_CASE
static final int MAX_RETRIES = 3;
// Packages: lowercase
package com.company.project;
```
### Formatting
```java
// Use 4 spaces for indentation
// Line length: ~100 characters max
// One declaration per line
int age;
String name;
// Braces always
if (condition) {
doSomething();
} else {
doOther();
}
```
## Encapsulation
### Always Use It
```java
// Good: private fields, public getters/setters
public class Person {
private String name;
private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) {
if (age >= 0) this.age = age;
}
}
// Bad: public fields
public class Person {
public String name; // No encapsulation!
}
```
## Immutable Objects
### When Possible
```java
// Immutable class
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
```
## Null Handling
### Null Checks
```java
// Objects.requireNonNull
public void setName(String name) {
this.name = Objects.requireNonNull(name, "Name cannot be null");
}
// Optional (Java 8+)
public Optional getNickname() {
return Optional.ofNullable(nickname);
}
// String check
if (name != null && !name.isEmpty()) { }
// Java 15+ Text Blocks
String json = """
{"name": "Alice"}
""";
```
## Collections Best Practices
### Interface Types
```java
// Use interface type
List list = new ArrayList<>();
Map map = new HashMap<>();
Set set = new HashSet<>();
// Don't use concrete type on left side
// ArrayList list = new ArrayList<>(); // Less flexible
```
### Diamond Operator
```java
// Java 7+
List list = new ArrayList<>();
// Without diamond (verbose)
List list = new ArrayList();
```
## Exception Handling
### Specific Exceptions
```java
// Good
try {
Integer.parseInt(str);
} catch (NumberFormatException e) {
// Handle invalid number
}
// Bad - catches everything
try {
Integer.parseInt(str);
} catch (Exception e) { }
```
### Don't Swallow Exceptions
```java
// Bad
try {
doSomething();
} catch (Exception e) {
// Silent failure - bad!
}
// Good - log and rethrow or handle
try {
doSomething();
} catch (Exception e) {
logger.error("Operation failed", e);
throw new RuntimeException(e);
}
```
## String Handling
### Use StringBuilder
```java
// For multiple concatenations
StringBuilder sb = new StringBuilder();
for (String word : words) {
sb.append(word).append(" ");
}
String result = sb.toString();
// Not: result += word + " "; // Creates many intermediate strings
```
### String Methods
```java
// Check content
str.contains("abc");
str.startsWith("Hello");
str.endsWith("World");
// Null-safe
Objects.toString(obj, "default");
```
## Performance
### Avoid Unnecessary Objects
```java
// Bad - creates many strings
String result = "";
for (String s : list) {
result += s + ",";
}
// Good
StringBuilder sb = new StringBuilder();
for (String s : list) {
if (sb.length() > 0) sb.append(",");
sb.append(s);
}
String result = sb.toString();
```
### Use Primitives When Possible
```java
// Use int not Integer when you don't need null
int count = 0; // Primitive
Integer count = null; // Only if you need null
```
## Effective Testing
### Unit Testing
```java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
@Test
void testDivideByZero() {
Calculator calc = new Calculator();
assertThrows(ArithmeticException.class,
() -> calc.divide(1, 0));
}
}
```
## Documentation
### Javadoc
```java
/**
* Calculates the area of a rectangle.
*
* @param width the width of the rectangle
* @param height the height of the rectangle
* @return the area (width * height)
* @throws IllegalArgumentException if width or height is negative
*/
public double rectangleArea(double width, double height) {
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Dimensions must be positive");
}
return width * height;
}
```
## Effective toString
```java
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// Or (Java 16+)
record Person(String name, int age) { }
```
## Logging
### Use Logger
```java
import java.util.logging.Logger;
public class MyClass {
private static final Logger logger = Logger.getLogger(MyClass.class.getName());
public void doSomething() {
logger.info("Starting operation");
// code
logger.warning("Potential issue");
}
}
```
## Summary
- Use meaningful names
- Encapsulate: private fields, public methods
- Prefer immutable objects
- Handle null explicitly
- Use interface types for variables
- Catch specific exceptions
- Never silently swallow exceptions
- Use StringBuilder for multiple concatenations
- Write unit tests
- Document public APIs with Javadoc
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →