java-best-practices について
Java 開発者向けの実践ガイドで、コードレビュー、実装、リファクタリング、設計判断を支援します。SOLID、Clean Code、テスト戦略、Java 固有のパターン、Spring Framework を扱います。
主な機能
- 01SOLID と DRY の原則
- 02Clean Code の指針
- 03Java 8 以降の機能活用
- 04テストとテスト容易性の指針
- 05Spring Framework の実践
活用シーン
- 01Java プロジェクトのコードレビュー
- 02Java コードの作成やリファクタリング
- 03アーキテクチャと設計判断の評価
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ clostaunau/ holiday-card --skill java-best-practicesインストール後、Claude Code で/java-best-practicesを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
templates/builder-pattern.javaREADME.mdservice-template.javatest-template.java詳細
Java のベストプラクティス
目的
このスキルは、Java 開発に関する包括的なベストプラクティスを提供し、コードレビューやアーキテクチャ上の判断におけるリファレンスガイドとして機能します。SOLID 原則、DRY、クリーンコード、Java 固有のパターン、テスト戦略、よくあるアンチパターンを取り上げます。
このスキルを使用する場面:
- Java プロジェクトのコードレビューを行うとき
- 新しい Java コードを書くとき
- 既存の Java コードをリファクタリングするとき
- アーキテクチャや設計上の判断を評価するとき
- チームメンバーに Java のベストプラクティスを教えるとき
- Spring Framework アプリケーションを扱うとき
コンテキスト
保守性、拡張性、堅牢性に優れたアプリケーションを構築するには、高品質な Java コードが欠かせません。このスキルでは、以下を重視する業界標準のプラクティスをまとめています。
- SOLID 原則:適切に設計されたオブジェクト指向コードの基礎
- クリーンコード:読みやすく、保守しやすく、自己説明的なコード
- Java 固有の機能:最新の Java 機能(8 以降)の適切な使用
- テスト容易性:テストと検証が容易なコード
- パフォーマンス:Java 言語と JVM の機能を効率的に使用すること
- Spring Framework:Spring ベースのアプリケーションにおけるベストプラクティス
このスキルは、コードレビュー時に uncle-duke-java エージェントが参照するほか、開発者が Java コードを書く際にも参照できるよう設計されています。
前提条件
必要な知識:
- Java の基礎(Java 8 以降)
- オブジェクト指向プログラミングの概念
- デザインパターンの基本的な理解
- Spring Framework の知識(Spring 固有のセクションの場合)
必要なツール:
- JDK 8 以降(11、17、21 を推奨)
- ビルド管理用の Maven または Gradle
- テスト用の JUnit 5
- モック用の Mockito
- Java に対応した IDE(IntelliJ IDEA、Eclipse、VS Code)
想定されるプロジェクト構成:
project/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/
│ │ │ ├── model/
│ │ │ ├── service/
│ │ │ ├── repository/
│ │ │ ├── controller/
│ │ │ └── util/
│ │ └── resources/
│ │ └── application.properties
│ └── test/
│ └── java/
│ └── com/example/
├── pom.xml (or build.gradle)
└── README.md
Java における SOLID 原則
単一責任の原則(SRP)
ルール: クラスが変更される理由は 1 つだけであるべきです。各クラスには、明確に定義された単一の責任を持たせます。
重要な理由: 複数の責任を持つクラスは、理解、テスト、保守が困難になります。ある責任に対する変更が、ほかの責任に影響する可能性があります。
実践における SRP
❌ 悪い例 - 複数の責任:
// This class violates SRP: it handles user data, validation, persistence, and email
public class User {
private String email;
private String password;
// Responsibility 1: Data validation
public boolean isValid() {
return email != null && email.contains("@")
&& password != null && password.length() >= 8;
}
// Responsibility 2: Database operations
public void save() {
Connection conn = DriverManager.getConnection("jdbc:...");
PreparedStatement ps = conn.prepareStatement("INSERT INTO users...");
ps.setString(1, email);
ps.setString(2, password);
ps.executeUpdate();
}
// Responsibility 3: Email operations
public void sendWelcomeEmail() {
EmailService.send(email, "Welcome!", "Welcome to our app");
}
// Responsibility 4: Password encryption
public void encryptPassword() {
this.password = BCrypt.hashpw(password, BCrypt.gensalt());
}
}
問題点:
- User クラスが 4 つの責任(データ、検証、永続化、メール)を持っています
- 検証ロジックの変更が User クラスに影響します
- データベーススキーマの変更が User クラスに影響します
- メールテンプレートの変更が User クラスに影響します
- 個々の責任をテストするのが困難です
✅ 良い例 - 単一の責任:
// Responsibility: Hold user data
public class User {
private final String email;
private final String passwordHash;
public User(String email, String passwordHash) {
this.email = email;
this.passwordHash = passwordHash;
}
public String getEmail() { return email; }
public String getPasswordHash() { return passwordHash; }
}
// Responsibility: Validate user data
public class UserValidator {
public ValidationResult validate(String email, String password) {
List<String> errors = new ArrayList<>();
if (email == null || !email.contains("@")) {
errors.add("Invalid email format");
}
if (password == null || password.length() < 8) {
errors.add("Password must be at least 8 characters");
}
return new ValidationResult(errors.isEmpty(), errors);
}
}
// Responsibility: Persist user data
public class UserRepository {
private final DataSource dataSource;
public UserRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
public void save(User user) {
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO users (email, password_hash) VALUES (?, ?)")) {
ps.setString(1, user.getEmail());
ps.setString(2, user.getPasswordHash());
ps.executeUpdate();
} catch (SQLException e) {
throw new DataAccessException("Failed to save user", e);
}
}
}
// Responsibility: Send emails
public class EmailService {
public void sendWelcomeEmail(User user) {
send(user.getEmail(), "Welcome!", "Welcome to our app");
}
private void send(String to, String subject, String body) {
// Email sending logic
}
}
// Responsibility: Hash passwords
public class PasswordEncoder {
public String encode(String rawPassword) {
return BCrypt.hashpw(rawPassword, BCrypt.gensalt());
}
public boolean matches(String rawPassword, String encodedPassword) {
return BCrypt.checkpw(rawPassword, encodedPassword);
}
}
利点:
- 各クラスに明確な責任が 1 つあります
- 各責任を独立して簡単にテストできます
- ある関心事への変更がほかに影響しません
- クラスが小さく、目的に集中しています
開放/閉鎖の原則(OCP)
ルール: ソフトウェアの構成要素(クラス、モジュール、関数)は、拡張に対して開かれ、変更に対して閉じられているべきです。
重要な理由: 既存のコードを変更せずに新しい機能を追加できるため、既存機能を壊すリスクを減らせます。
実践における OCP
❌ 悪い例 - OCP 違反:
public class PaymentProcessor {
public void processPayment(String paymentType, double amount) {
if (paymentType.equals("CREDIT_CARD")) {
// Process credit card payment
System.out.println("Processing credit card payment: $" + amount);
} else if (paymentType.equals("PAYPAL")) {
// Process PayPal payment
System.out.println("Processing PayPal payment: $" + amount);
} else if (paymentType.equals("BITCOIN")) {
// Process Bitcoin payment
System.out.println("Processing Bitcoin payment: $" + amount);
}
// Adding new payment method requires modifying this class!
}
}
問題点:
- 新しい支払い方法を追加するには PaymentProcessor の変更が必要です
- OCP に違反しています(変更に対して閉じられていません)
- if-else の連鎖が増えていきます
- 個々の支払い方法をテストするのが困難です
✅ 良い例 - OCP に準拠:
// Abstract payment interface
public interface PaymentMethod {
void process(double amount);
}
// Concrete implementations
public class CreditCardPayment implements PaymentMethod {
@Override
public void process(double amount) {
System.out.println("Processing credit card payment: $" + amount);
// Credit card specific logic
}
}
public class PayPalPayment implements PaymentMethod {
@Override
public void process(double amount) {
System.out.println("Processing PayPal payment: $" + amount);
// PayPal specific logic
}
}
public class BitcoinPayment implements PaymentMethod {
@Override
public void process(double amount) {
System.out.println("Processing Bitcoin payment: $" + amount);
// Bitcoin specific logic
}
}
// Processor delegates to payment method
public class PaymentProcessor {
public void processPayment(PaymentMethod paymentMethod, double amount) {
paymentMethod.process(amount);
}
}
// Usage
PaymentProcessor processor = new PaymentProcessor();
processor.processPayment(new CreditCardPayment(), 100.0);
processor.processPayment(new PayPalPayment(), 50.0);
// Adding new payment method: just create new class, no modification needed!
public class ApplePayPayment implements PaymentMethod {
@Override
public void process(double amount) {
System.out.println("Processing Apple Pay payment: $" + amount);
}
}
利点:
- 既存のコードを変更せずに、新しい支払い方法を追加できます
- 各支払い方法を個別にテストできます
- OCP に準拠しています:拡張に対して開かれ、変更に対して閉じられています
- 関心事が明確に分離されています
ストラテジーパターンによる OCP
✅ 応用例 - 割引ストラテジー:
// Strategy interface
public interface DiscountStrategy {
double applyDiscount(double price);
}
// Concrete strategies
public class NoDiscount implements DiscountStrategy {
@Override
public double applyDiscount(double price) {
return price;
}
}
public class PercentageDiscount implements DiscountStrategy {
private final double percentage;
public PercentageDiscount(double percentage) {
this.percentage = percentage;
}
@Override
public double applyDiscount(double price) {
return price * (1 - percentage / 100);
}
}
public class FixedAmountDiscount implements DiscountStrategy {
private final double amount;
public FixedAmountDiscount(double amount) {
this.amount = amount;
}
@Override
public double applyDiscount(double price) {
return Math.max(0, price - amount);
}
}
// Context uses strategy
public class PriceCalculator {
private final DiscountStrategy discountStrategy;
public PriceCalculator(DiscountStrategy discountStrategy) {
this.discountStrategy = discountStrategy;
}
public double calculateFinalPrice(double originalPrice) {
return discountStrategy.applyDiscount(originalPrice);
}
}
// Usage
PriceCalculator calc1 = new PriceCalculator(new PercentageDiscount(10));
double price1 = calc1.calculateFinalPrice(100); // 90.0
PriceCalculator calc2 = new PriceCalculator(new FixedAmountDiscount(15));
double price2 = calc2.calculateFinalPrice(100); // 85.0
リスコフの置換原則(LSP)
ルール: アプリケーションを壊すことなく、スーパークラスのオブジェクトをサブクラスのオブジェクトに置き換えられるべきです。サブタイプは、基底型の代わりに使用できなければなりません。
重要な理由: LSP に違反すると予期しない動作が発生し、ポリモーフィズムが機能しなくなります。
実践における LSP
❌ 悪い例 - LSP に違反しています:
public class Rectangle {
protected int width;
protected int height;
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public int getArea() {
return width * height;
}
}
// Square violates LSP because it changes behavior of setters
public class Square extends Rectangle {
@Override
public void setWidth(int width) {
this.width = width;
this.height = width; // Side effect!
}
@Override
public void setHeight(int height) {
this.width = height; // Side effect!
this.height = height;
}
}
// This test works for Rectangle but fails for Square
public void testRectangle(Rectangle rect) {
rect.setWidth(5);
rect.setHeight(4);
assertEquals(20, rect.getArea()); // Fails for Square! (25 instead of 20)
}
問題点:
- Square が Rectangle のメソッドの動作を変更しています
- Rectangle の代わりに Square を使用できません
- LSP に違反し、ポリモーフィズムを損ないます
✅ 良い例 - LSP に従っています:
// Common interface for shapes
public interface Shape {
int getArea();
}
// Rectangle implementation
public class Rectangle implements Shape {
private final int width;
private final int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public int getArea() {
return width * height;
}
public int getWidth() { return width; }
public int getHeight() { return height; }
}
// Square implementation (no inheritance from Rectangle)
public class Square implements Shape {
private final int side;
public Square(int side) {
this.side = side;
}
@Override
public int getArea() {
return side * side;
}
public int getSide() { return side; }
}
// Works for any Shape
public int calculateTotalArea(List<Shape> shapes) {
return shapes.stream()
.mapToInt(Shape::getArea)
.sum();
}
利点:
- Square と Rectangle は独立しています
- どちらも Shape の契約を正しく実装しています
- 任意の Shape 実装と置き換えられます
- 想定外の動作がありません
LSP - 事前条件と事後条件
✅ 良い例 - 契約を維持しています:
public interface BankAccount {
// Precondition: amount > 0
// Postcondition: balance increased by amount
void deposit(double amount);
// Precondition: amount > 0 and amount <= balance
// Postcondition: balance decreased by amount
void withdraw(double amount) throws InsufficientFundsException;
double getBalance();
}
public class SavingsAccount implements BankAccount {
private double balance;
@Override
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive");
}
balance += amount;
}
@Override
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive");
}
if (amount > balance) {
throw new InsufficientFundsException();
}
balance -= amount;
}
@Override
public double getBalance() {
return balance;
}
}
// Subclass maintains contracts (LSP)
public class CheckingAccount implements BankAccount {
private double balance;
private final double overdraftLimit;
public CheckingAccount(double overdraftLimit) {
this.overdraftLimit = overdraftLimit;
}
@Override
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive");
}
balance += amount; // Same postcondition
}
@Override
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive");
}
// Can weaken precondition (allow overdraft) but not strengthen
if (amount > balance + overdraftLimit) {
throw new InsufficientFundsException();
}
balance -= amount; // Same postcondition
}
@Override
public double getBalance() {
return balance;
}
}
インターフェース分離の原則(ISP)
ルール: クライアントに、使用しないインターフェースへの依存を強制してはいけません。汎用インターフェースを 1 つ用意するより、具体的なインターフェースを複数用意するほうが適切です。
重要な理由: 大きなインターフェースは、実装に不要なメソッドの提供を強制し、空の実装や密結合につながります。
実践における ISP
❌ 悪い例 - 肥大化したインターフェース:
// Fat interface forces all implementations to provide all methods
public interface Worker {
void work();
void eat();
void sleep();
void getSalary();
void attendMeeting();
}
// Robot doesn't eat or sleep but is forced to implement these methods
public class RobotWorker implements Worker {
@Override
public void work() {
System.out.println("Robot working");
}
@Override
public void eat() {
// Doesn't make sense for robots!
throw new UnsupportedOperationException("Robots don't eat");
}
@Override
public void sleep() {
// Doesn't make sense for robots!
throw new UnsupportedOperationException("Robots don't sleep");
}
@Override
public void getSalary() {
throw new UnsupportedOperationException("Robots don't get paid");
}
@Override
public void attendMeeting() {
System.out.println("Robot attending meeting");
}
}
問題点:
- Robot に生物としてのメソッドの実装を強制しています
- UnsupportedOperationException をスローするのはコードの臭いです
- ISP に違反しています
- 無関係なメソッドとの密結合が生じています
✅ 良い例 - 分離されたインターフェース:
// Segregated interfaces - clients depend only on what they need
public interface Workable {
void work();
}
public interface Eatable {
void eat();
}
public interface Sleepable {
void sleep();
}
public interface Payable {
void getSalary();
}
public interface MeetingAttendee {
void attendMeeting();
}
// Human implements relevant interfaces
public class HumanWorker implements Workable, Eatable, Sleepable, Payable, MeetingAttendee {
@Override
public void work() {
System.out.println("Human working");
}
@Override
public void eat() {
System.out.println("Human eating");
}
@Override
public void sleep() {
System.out.println("Human sleeping");
}
@Override
public void getSalary() {
System.out.println("Human receiving salary");
}
@Override
public void attendMeeting() {
System.out.println("Human attending meeting");
}
}
// Robot only implements relevant interfaces
public class RobotWorker implements Workable, MeetingAttendee {
@Override
public void work() {
System.out.println("Robot working");
}
@Override
public void attendMeeting() {
System.out.println("Robot attending meeting");
}
}
利点:
- 実装では、意味のあるメソッドだけを提供します
- UnsupportedOperationException は不要です
- 関心事が明確に分離されます
- 柔軟に組み合わせられます
依存性逆転の原則(DIP)
ルール: 高レベルモジュールは低レベルモジュールに依存してはいけません。両者は抽象に依存する必要があります。抽象は詳細に依存してはいけません。詳細は抽象に依存する必要があります。
重要な理由: DIP によってコードの結合が弱まり、柔軟性、テスト容易性、保守性が高まります。
実践における DIP
❌ 悪い例 - 高レベルが低レベルに依存しています:
// Low-level module
public class MySQLDatabase {
public void save(String data) {
System.out.println("Saving to MySQL: " + data);
}
}
// High-level module depends on concrete low-level module
public class UserService {
private MySQLDatabase database; // Concrete dependency!
public UserService() {
this.database = new MySQLDatabase(); // Tight coupling!
}
public void createUser(String userData) {
// Business logic
database.save(userData);
}
}
問題点:
- UserService が MySQLDatabase に密結合しています
- UserService を変更せずに PostgreSQL に切り替えることができません
- テストが困難です(データベースをモックできません)
- DIP に違反しています
✅ 良い例 - 両者が抽象に依存しています:
// Abstraction
public interface Database {
void save(String data);
}
// Low-level modules depend on abstraction
public class MySQLDatabase implements Database {
@Override
public void save(String data) {
System.out.println("Saving to MySQL: " + data);
}
}
public class PostgreSQLDatabase implements Database {
@Override
public void save(String data) {
System.out.println("Saving to PostgreSQL: " + data);
}
}
public class MongoDatabase implements Database {
@Override
public void save(String data) {
System.out.println("Saving to MongoDB: " + data);
}
}
// High-level module depends on abstraction
public class UserService {
private final Database database; // Abstraction!
// Dependency injected through constructor
public UserService(Database database) {
this.database = database;
}
public void createUser(String userData) {
// Business logic
database.save(userData);
}
}
// Usage - client chooses implementation
Database db = new MySQLDatabase();
UserService service = new UserService(db);
service.createUser("John Doe");
// Easy to switch implementations
Database postgresDb = new PostgreSQLDatabase();
UserService postgresService = new UserService(postgresDb);
// Easy to test with mock
Database mockDb = mock(Database.class);
UserService testService = new UserService(mockDb);
利点:
- UserService がデータベースの実装から切り離されています
- データベースの実装を簡単に切り替えられます
- モックを使って簡単にテストできます
- DIP に従っています
Spring Framework における SOLID 原則
Spring Framework は SOLID 原則、特に依存性逆転の原則に基づいて構築されています。
Spring における依存性注入
✅ Spring DI の例:
// Abstraction
public interface UserRepository {
User findById(Long id);
void save(User user);
}
// Implementation
@Repository
public class JpaUserRepository implements UserRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public User findById(Long id) {
return entityManager.find(User.class, id);
}
@Override
public void save(User user) {
entityManager.persist(user);
}
}
// Service depends on abstraction
@Service
public class UserService {
private final UserRepository userRepository;
// Constructor injection (recommended)
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getUser(Long id) {
return userRepository.findById(id);
}
}
// Controller depends on service abstraction
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.getUser(id);
return ResponseEntity.ok(user);
}
}
Spring DI のベストプラクティス:
- コンストラクターインジェクションを使用します(必須の依存関係、不変性)
- フィールドインジェクションはオプションの依存関係に限って使用することを推奨します
- 具象クラスではなく、インターフェースに依存します
- 複数の実装がある場合は
@Qualifierを使用します
DRY(同じことを繰り返さない)
ルール: 知識の各要素は、システム内に単一の、曖昧さのない、信頼できる表現を持つ必要があります。
重要な理由: 重複は不整合を招き、保守を難しくし、バグを増やします。
コードの重複を見つける
❌ 悪い例 - 明らかな重複:
public class OrderService {
public void processOnlineOrder(Order order) {
// Validate
if (order == null) {
throw new IllegalArgumentException("Order cannot be null");
}
if (order.getItems().isEmpty()) {
throw new IllegalArgumentException("Order must have items");
}
if (order.getTotalAmount() <= 0) {
throw new IllegalArgumentException("Order total must be positive");
}
// Process
System.out.println("Processing online order: " + order.getId());
order.setStatus(OrderStatus.PROCESSING);
saveOrder(order);
}
public void processPhoneOrder(Order order) {
// Same validation - DUPLICATION!
if (order == null) {
throw new IllegalArgumentException("Order cannot be null");
}
if (order.getItems().isEmpty()) {
throw new IllegalArgumentException("Order must have items");
}
if (order.getTotalAmount() <= 0) {
throw new IllegalArgumentException("Order total must be positive");
}
// Process
System.out.println("Processing phone order: " + order.getId());
order.setStatus(OrderStatus.PROCESSING);
saveOrder(order);
}
}
✅ 良い例 - 共通ロジックを抽出します:
public class OrderService {
public void processOnlineOrder(Order order) {
validateOrder(order);
processOrder(order, "online");
}
public void processPhoneOrder(Order order) {
validateOrder(order);
processOrder(order, "phone");
}
private void validateOrder(Order order) {
if (order == null) {
throw new IllegalArgumentException("Order cannot be null");
}
if (order.getItems().isEmpty()) {
throw new IllegalArgumentException("Order must have items");
}
if (order.getTotalAmount() <= 0) {
throw new IllegalArgumentException("Order total must be positive");
}
}
private void processOrder(Order order, String type) {
System.out.println("Processing " + type + " order: " + order.getId());
order.setStatus(OrderStatus.PROCESSING);
saveOrder(order);
}
}
ユーティリティクラスとヘルパーメソッド
✅ 再利用可能なロジックにはユーティリティクラスを作成します:
public final class StringUtils {
private StringUtils() {
// Prevent instantiation
}
public static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
public static String capitalize(String str) {
if (isBlank(str)) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
public static String truncate(String str, int maxLength) {
if (str == null || str.length() <= maxLength) {
return str;
}
return str.substring(0, maxLength) + "...";
}
}
// Usage
if (StringUtils.isBlank(username)) {
throw new ValidationException("Username is required");
}
String displayName = StringUtils.capitalize(name);
再利用性のためのジェネリクス
✅ 重複を避けるためにジェネリクスを使用します:
// Instead of creating separate classes for different types
public class GenericRepository<T, ID> {
private final Class<T> entityClass;
@PersistenceContext
private EntityManager entityManager;
public GenericRepository(Class<T> entityClass) {
this.entityClass = entityClass;
}
public Optional<T> findById(ID id) {
T entity = entityManager.find(entityClass, id);
return Optional.ofNullable(entity);
}
public List<T> findAll() {
CriteriaQuery<T> query = entityManager.getCriteriaBuilder()
.createQuery(entityClass);
query.select(query.from(entityClass));
return entityManager.createQuery(query).getResultList();
}
public void save(T entity) {
entityManager.persist(entity);
}
public void delete(T entity) {
entityManager.remove(entity);
}
}
// Concrete repositories extend generic repository
@Repository
public class UserRepository extends GenericRepository<User, Long> {
public UserRepository() {
super(User.class);
}
// Add User-specific queries
public Optional<User> findByEmail(String email) {
// Custom query
}
}
クリーンコードの原則
意味が明確な名前
ルール: 名前から意図が伝わり、発音しやすく、検索しやすいものにします。
❌ 悪い名前:
int d; // elapsed time in days
String yyyymmdd;
List<int[]> list1;
public void getData() {
// What data?
}
✅ 良い名前:
int elapsedTimeInDays;
String formattedDate;
List<Customer> activeCustomers;
public Customer getCustomerById(Long customerId) {
// Clear what this method does
}
命名規則
// Classes: PascalCase, nouns
public class CustomerService { }
public class OrderRepository { }
// Interfaces: PascalCase, often adjectives or nouns
public interface Serializable { }
public interface UserRepository { }
// Methods: camelCase, verbs
public void calculateTotal() { }
public Customer findCustomerById(Long id) { }
// Variables: camelCase, nouns
String customerName;
int orderCount;
boolean isActive;
// Constants: UPPER_SNAKE_CASE
public static final int MAX_RETRY_COUNT = 3;
public static final String DEFAULT_ENCODING = "UTF-8";
// Packages: lowercase, periods
package com.example.service;
package com.example.repository;
// Boolean methods/variables: is, has, can
boolean isValid();
boolean hasPermission();
boolean canExecute();
関数のサイズと複雑さ
ルール: 関数は小さく保ち、1 つのことだけを行うようにします。メソッドは 5~20 行を目安にします。
❌ 悪い例 - 大きく複雑なメソッド:
public void processOrder(Order order) {
// Validation
if (order == null) throw new IllegalArgumentException();
if (order.getItems().isEmpty()) throw new IllegalArgumentException();
// Calculate total
double total = 0;
for (OrderItem item : order.getItems()) {
double itemPrice = item.getPrice();
int quantity = item.getQuantity();
double discount = item.getDiscount();
total += (itemPrice * quantity) * (1 - discount);
}
order.setTotal(total);
// Apply coupon
if (order.getCoupon() != null) {
String couponCode = order.getCoupon().getCode();
if (couponCode.startsWith("SAVE")) {
total *= 0.9;
} else if (couponCode.startsWith("BIG")) {
total *= 0.8;
}
order.setTotal(total);
}
// Check inventory
for (OrderItem item : order.getItems()) {
int available = inventoryService.getAvailableQuantity(item.getProductId());
if (available < item.getQuantity()) {
throw new InsufficientInventoryException();
}
}
// Save order
orderRepository.save(order);
// Send email
emailService.send(order.getCustomer().getEmail(), "Order Confirmation",
"Your order " + order.getId() + " has been confirmed");
// Update inventory
for (OrderItem item : order.getItems()) {
inventoryService.decrementQuantity(item.getProductId(), item.getQuantity());
}
}
✅ 良い例 - 小さく、目的を絞ったメソッド:
public void processOrder(Order order) {
validateOrder(order);
calculateOrderTotal(order);
applyCouponDiscount(order);
checkInventoryAvailability(order);
saveOrder(order);
sendConfirmationEmail(order);
updateInventory(order);
}
private void validateOrder(Order order) {
if (order == null) {
throw new IllegalArgumentException("Order cannot be null");
}
if (order.getItems().isEmpty()) {
throw new IllegalArgumentException("Order must contain items");
}
}
private void calculateOrderTotal(Order order) {
double total = order.getItems().stream()
.mapToDouble(this::calculateItemTotal)
.sum();
order.setTotal(total);
}
private double calculateItemTotal(OrderItem item) {
return item.getPrice() * item.getQuantity() * (1 - item.getDiscount());
}
private void applyCouponDiscount(Order order) {
if (order.getCoupon() == null) {
return;
}
double discountMultiplier = getDiscountMultiplier(order.getCoupon());
order.setTotal(order.getTotal() * discountMultiplier);
}
private double getDiscountMultiplier(Coupon coupon) {
String code = coupon.getCode();
if (code.startsWith("SAVE")) return 0.9;
if (code.startsWith("BIG")) return 0.8;
return 1.0;
}
private void checkInventoryAvailability(Order order) {
for (OrderItem item : order.getItems()) {
int available = inventoryService.getAvailableQuantity(item.getProductId());
if (available < item.getQuantity()) {
throw new InsufficientInventoryException(
"Product " + item.getProductId() + " has insufficient inventory");
}
}
}
private void saveOrder(Order order) {
orderRepository.save(order);
}
private void sendConfirmationEmail(Order order) {
String email = order.getCustomer().getEmail();
String subject = "Order Confirmation";
String body = String.format("Your order %s has been confirmed", order.getId());
emailService.send(email, subject, body);
}
private void updateInventory(Order order) {
order.getItems().forEach(item ->
inventoryService.decrementQuantity(item.getProductId(), item.getQuantity())
);
}
利点:
- 各メソッドの目的が明確で、1 つに絞られています
- 理解しやすく、テストも簡単です
- メインメソッドを目次のように読み進められます
- ヘルパーメソッドを再利用できます
コメントのベストプラクティス
ルール: コードは自己説明的であるべきです。コメントでは「何を」ではなく「なぜ」を説明します。
❌ 悪いコメント:
// Set the flag to true
isActive = true;
// Loop through users
for (User user : users) {
// Check if user is active
if (user.isActive()) {
// Add to list
activeUsers.add(user);
}
}
// This is the UserService class
public class UserService {
}
✅ 良いコメント:
// No comment needed - code is self-explanatory
isActive = true;
List<User> activeUsers = users.stream()
.filter(User::isActive)
.collect(Collectors.toList());
// Good: Explains WHY, not WHAT
// We use exponential backoff to avoid overwhelming the external API
// after multiple failures (circuit breaker pattern)
private int calculateRetryDelay(int attemptNumber) {
return (int) Math.pow(2, attemptNumber) * 1000;
}
// Good: JavaDoc for public API
/**
* Transfers funds between accounts atomically.
*
* @param fromAccount source account (must have sufficient balance)
* @param toAccount destination account
* @param amount amount to transfer (must be positive)
* @throws InsufficientFundsException if source account lacks funds
* @throws IllegalArgumentException if amount is negative or zero
*/
public void transferFunds(Account fromAccount, Account toAccount, double amount)
throws InsufficientFundsException {
// Implementation
}
// Good: Explains non-obvious business rule
// Tax calculation excludes shipping but includes discount adjustments
// per IRS regulation 2024-15
double taxableAmount = subtotal - discount;
コメントを記述する場面:
- パブリック API(JavaDoc)
- 複雑なアルゴリズム(アプローチを説明)
- ビジネスルール(規制要件)
- 回避策(回避策が必要な理由)
- TODO/FIXME(チケット番号付き)
コメントを記述しない場面:
- 明らかなコード
- コメントアウトされたコード(削除して、バージョン管理を利用してください)
- 変更履歴(git を利用してください)
エラー処理
ルール: 例外的なケースには例外を使用します。制御フローには例外を使用しないでください。
❌ 悪いエラー処理:
// Using exceptions for control flow
public User findUser(Long id) {
try {
return userRepository.findById(id);
} catch (NotFoundException e) {
return null; // Swallowing exception
}
}
// Catching generic Exception
public void processData(String data) {
try {
// Complex logic
} catch (Exception e) {
// Too broad!
}
}
// Empty catch block
try {
riskyOperation();
} catch (IOException e) {
// Ignored - NEVER DO THIS
}
✅ 良いエラー処理:
// Use Optional for "not found" scenarios
public Optional<User> findUser(Long id) {
return userRepository.findById(id);
}
// Catch specific exceptions
public void processData(String data) {
try {
parseAndValidate(data);
saveToDatabase(data);
} catch (JsonParseException e) {
log.error("Failed to parse JSON data: {}", data, e);
throw new DataProcessingException("Invalid JSON format", e);
} catch (DataAccessException e) {
log.error("Database error while saving data", e);
throw new DataProcessingException("Failed to save data", e);
}
}
// Always handle or rethrow exceptions
try {
riskyOperation();
} catch (IOException e) {
log.error("Operation failed", e);
throw new ApplicationException("Failed to perform operation", e);
}
// Use try-with-resources for auto-closeable resources
public String readFile(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
return reader.lines().collect(Collectors.joining("\n"));
}
// Reader automatically closed, even if exception occurs
}
コードの構成
ルール: クラス内のコードを論理的に整理します。関連するメソッドは近くに配置します。
✅ クラス構成の例:
public class UserService {
// 1. Constants
private static final int MAX_LOGIN_ATTEMPTS = 3;
private static final long LOCKOUT_DURATION_MINUTES = 30;
// 2. Static fields
private static final Logger log = LoggerFactory.getLogger(UserService.class);
// 3. Instance fields
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final EmailService emailService;
// 4. Constructors
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
EmailService emailService) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.emailService = emailService;
}
// 5. Public methods (grouped by functionality)
// User creation methods
public User registerUser(UserRegistrationDto dto) {
validateRegistration(dto);
User user = createUser(dto);
sendWelcomeEmail(user);
return user;
}
// User authentication methods
public AuthToken login(String email, String password) {
User user = findUserByEmail(email);
validatePassword(user, password);
return generateAuthToken(user);
}
// 6. Private helper methods (near methods that use them)
private void validateRegistration(UserRegistrationDto dto) {
// Validation logic
}
private User createUser(UserRegistrationDto dto) {
// Creation logic
}
private void sendWelcomeEmail(User user) {
emailService.send(user.getEmail(), "Welcome!", getWelcomeEmailBody());
}
private User findUserByEmail(String email) {
return userRepository.findByEmail(email)
.orElseThrow(() -> new UserNotFoundException(email));
}
private void validatePassword(User user, String password) {
if (!passwordEncoder.matches(password, user.getPasswordHash())) {
throw new AuthenticationException("Invalid password");
}
}
private AuthToken generateAuthToken(User user) {
// Token generation logic
}
private String getWelcomeEmailBody() {
return "Welcome to our application!";
}
}
Java 固有のベストプラクティス
null の代わりに Optional を使用する
ルール: 存在しない可能性がある値を表すには Optional<T> を使用します。コレクションに対して null を返してはいけません。
❌ 悪い例 - null を返す:
public User findUser(Long id) {
User user = database.find(id);
return user; // May return null!
}
// Caller must remember to check null
User user = findUser(123L);
if (user != null) {
// Use user
}
✅ 良い例 - Optional を使用する:
public Optional<User> findUser(Long id) {
User user = database.find(id);
return Optional.ofNullable(user);
}
// Caller forced to handle absence
Optional<User> userOpt = findUser(123L);
// Method 1: ifPresent
userOpt.ifPresent(user -> System.out.println(user.getName()));
// Method 2: orElse
User user = userOpt.orElse(createDefaultUser());
// Method 3: orElseThrow
User user = userOpt.orElseThrow(() ->
new UserNotFoundException("User 123 not found"));
// Method 4: map/flatMap
String email = userOpt
.map(User::getEmail)
.orElse("[email protected]");
Optional のベストプラクティス:
- 値が見つからない可能性のあるメソッドでは、
Optional<T>を返す - フィールドに
Optionalを使用しない - メソッドのパラメーターとして
Optionalを渡さない Optionalを返すメソッドから null を返さないOptional.ofNullable(null)ではなくOptional.empty()を使用する
❌ Optional の悪い使用例:
// Don't use Optional as field
public class User {
private Optional<String> middleName; // BAD!
}
// Don't use Optional as parameter
public void setEmail(Optional<String> email) { // BAD!
}
// Don't call get() without checking
Optional<User> userOpt = findUser(id);
User user = userOpt.get(); // May throw NoSuchElementException!
✅ Optional の良い使用例:
// Use null for optional fields (or use proper null handling)
public class User {
private String middleName; // Can be null
public Optional<String> getMiddleName() {
return Optional.ofNullable(middleName);
}
}
// Use regular parameter with @Nullable annotation
public void setEmail(@Nullable String email) {
this.email = email;
}
// Always check before get(), or use other methods
Optional<User> userOpt = findUser(id);
if (userOpt.isPresent()) {
User user = userOpt.get();
// Use user
}
// Or use orElse/orElseThrow/ifPresent
User user = userOpt.orElseThrow(() -> new NotFoundException());
継承よりコンポジションを優先する
ルール: 真の is-a 関係がある場合を除き、継承(is-a)よりコンポジション(has-a)を優先します。
❌ 悪い例 - 継承の乱用:
// Inheritance used just to reuse code (wrong!)
public class Stack extends ArrayList<Object> {
public void push(Object item) {
add(item);
}
public Object pop() {
return remove(size() - 1);
}
}
// Problems:
// 1. Stack exposes all ArrayList methods (add, remove, clear, etc.)
// 2. Stack IS-NOT-A ArrayList semantically
// 3. Breaks encapsulation
✅ 良い例 - コンポジション:
public class Stack<T> {
private final List<T> elements = new ArrayList<>();
public void push(T item) {
elements.add(item);
}
public T pop() {
if (elements.isEmpty()) {
throw new EmptyStackException();
}
return elements.remove(elements.size() - 1);
}
public T peek() {
if (elements.isEmpty()) {
throw new EmptyStackException();
}
return elements.get(elements.size() - 1);
}
public boolean isEmpty() {
return elements.isEmpty();
}
public int size() {
return elements.size();
}
}
継承を使用する場面:
- 真の is-a 関係がある
- サブクラスがスーパークラスの特化版である
- リスコフの置換原則が成り立つ
コンポジションを使用する場面:
- 機能を再利用する
- has-a 関係がある
- 実装を柔軟に変更する必要がある
- 複数の振る舞いが必要である(複数を合成できるが、継承できるのは1つ)
final による不変性
ルール: 可能な場合は、クラスや変数を不変にします。final を積極的に使用します。
✅ 不変クラス:
public final class Money {
private final double amount;
private final String currency;
public Money(double amount, String currency) {
if (amount < 0) {
throw new IllegalArgumentException("Amount cannot be negative");
}
this.amount = amount;
this.currency = currency;
}
public double getAmount() {
return amount;
}
public String getCurrency() {
return currency;
}
// Return new instance instead of modifying
public Money add(Money other) {
if (!this.currency.equals(other.currency)) {
throw new IllegalArgumentException("Currency mismatch");
}
return new Money(this.amount + other.amount, this.currency);
}
public Money multiply(double multiplier) {
return new Money(this.amount * multiplier, this.currency);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Money)) return false;
Money money = (Money) o;
return Double.compare(money.amount, amount) == 0
&& currency.equals(money.currency);
}
@Override
public int hashCode() {
return Objects.hash(amount, currency);
}
}
不変性の利点:
- デフォルトでスレッドセーフ
- 安全に共有できる
- 理解しやすい
- 防御的コピーが不要
- HashMap のキーとして安全に使用できる
✅ 変数に final を使用する:
public void processOrder(Order order) {
final double total = order.getTotal();
final List<OrderItem> items = order.getItems();
// Compiler prevents reassignment
// total = 100; // Compilation error
// items = new ArrayList<>(); // Compilation error
// Note: final prevents reassignment, not mutation
items.add(new OrderItem()); // This is allowed!
// For true immutability, use Collections.unmodifiableList
final List<OrderItem> immutableItems =
Collections.unmodifiableList(new ArrayList<>(items));
}
Stream API の使用
ルール: コレクションの操作には Stream API を使用します。より読みやすく関数型であり、並列化も可能です。
❌ 悪い例 - 命令型スタイル:
List<User> activeUsers = new ArrayList<>();
for (User user : users) {
if (user.isActive()) {
activeUsers.add(user);
}
}
List<String> emails = new ArrayList<>();
for (User user : activeUsers) {
emails.add(user.getEmail());
}
Collections.sort(emails);
✅ 良い例 - Stream による宣言型スタイル:
List<String> emails = users.stream()
.filter(User::isActive)
.map(User::getEmail)
.sorted()
.collect(Collectors.toList());
✅ 一般的な Stream パターン:
// Filtering
List<Order> largeOrders = orders.stream()
.filter(order -> order.getTotal() > 1000)
.collect(Collectors.toList());
// Mapping
List<String> customerNames = orders.stream()
.map(order -> order.getCustomer().getName())
.collect(Collectors.toList());
// FlatMap (flatten nested collections)
List<OrderItem> allItems = orders.stream()
.flatMap(order -> order.getItems().stream())
.collect(Collectors.toList());
// Reduce (sum, average, etc.)
double totalRevenue = orders.stream()
.mapToDouble(Order::getTotal)
.sum();
Optional<Order> maxOrder = orders.stream()
.max(Comparator.comparing(Order::getTotal));
// Grouping
Map<String, List<Order>> ordersByStatus = orders.stream()
.collect(Collectors.groupingBy(Order::getStatus));
// Partitioning (special case of grouping - boolean)
Map<Boolean, List<Order>> ordersByShipped = orders.stream()
.collect(Collectors.partitioningBy(Order::isShipped));
// Find first/any
Optional<User> firstAdmin = users.stream()
.filter(User::isAdmin)
.findFirst();
// Distinct
List<String> uniqueCities = users.stream()
.map(User::getCity)
.distinct()
.collect(Collectors.toList());
// Limit and skip
List<User> firstTenUsers = users.stream()
.limit(10)
.collect(Collectors.toList());
// Combining operations
double averageOrderValueForActiveCustomers = orders.stream()
.filter(order -> order.getCustomer().isActive())
.mapToDouble(Order::getTotal)
.average()
.orElse(0.0);
Stream のベストプラクティス:
- Stream を再利用しない(パイプラインごとに新しい Stream を作成する)
- Stream 操作で副作用を避ける
- 可能な場合はメソッド参照を使用する
- 大規模なデータセットでは並列 Stream を検討する(ただし、計測してください!)
- Stream は遅延実行されるため、終端操作によって実行が開始される
❌ Stream の悪い使用例:
// Don't modify external state in streams
List<String> results = new ArrayList<>();
users.stream()
.forEach(user -> results.add(user.getName())); // Side effect!
// Use collect instead
List<String> results = users.stream()
.map(User::getName)
.collect(Collectors.toList());
// Don't reuse streams
Stream<User> userStream = users.stream();
long count = userStream.count(); // OK
List<User> list = userStream.collect(Collectors.toList()); // IllegalStateException!
ラムダ式
ルール: 関数型インターフェースにはラムダ式を使用します。該当する場合はメソッド参照を優先します。
✅ ラムダ式のベストプラクティス:
// Lambda expression
List<User> sorted = users.stream()
.sorted((u1, u2) -> u1.getName().compareTo(u2.getName()))
.collect(Collectors.toList());
// Better: Method reference
List<User> sorted = users.stream()
.sorted(Comparator.comparing(User::getName))
.collect(Collectors.toList());
// Lambda with multiple statements
users.forEach(user -> {
user.setLastLoginTime(LocalDateTime.now());
user.incrementLoginCount();
userRepository.save(user);
});
// Custom functional interface
@FunctionalInterface
public interface OrderProcessor {
void process(Order order);
}
OrderProcessor processor = order -> {
validateOrder(order);
calculateTotal(order);
saveOrder(order);
};
メソッド参照
ルール: 可能な場合はラムダ式の代わりにメソッド参照を使用します。より簡潔です。
// Lambda vs Method Reference
// Lambda: user -> user.getName()
// Method reference: User::getName
users.stream().map(User::getName);
// Lambda: user -> System.out.println(user)
// Method reference: System.out::println
users.forEach(System.out::println);
// Lambda: () -> new ArrayList<>()
// Method reference: ArrayList::new
Supplier<List<String>> supplier = ArrayList::new;
// Lambda: str -> str.length()
// Method reference: String::length
strings.stream().map(String::length);
メソッド参照の種類:
- 静的メソッド:
ClassName::staticMethod - 特定のオブジェクトのインスタンスメソッド:
object::instanceMethod - 任意のオブジェクトのインスタンスメソッド:
ClassName::instanceMethod - コンストラクター:
ClassName::new
try-with-resources
ルール: AutoCloseable リソースには必ず try-with-resources を使用します。
❌ 悪い例 - 手動でのリソース管理:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
// Process line
} catch (IOException e) {
log.error("Error reading file", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.error("Error closing reader", e);
}
}
}
✅ 良い例 - try-with-resources:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
// Process line
} catch (IOException e) {
log.error("Error reading file", e);
}
// Reader automatically closed, even if exception occurs
// Multiple resources
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {
// Use streams
} catch (IOException e) {
log.error("Error processing files", e);
}
// Both streams automatically closed in reverse order
StringBuilder と文字列連結の使い分け
ルール: ループ内で複数の文字列を連結する場合は StringBuilder を使用します。単純な連結には + を使用します。
❌ 悪い例 - ループ内での文字列連結:
String result = "";
for (int i = 0; i < 1000; i++) {
result += i + ","; // Creates 1000 new String objects!
}
✅ 良い例 - StringBuilder:
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
builder.append(i).append(",");
}
String result = builder.toString();
// Or use String.join for collections
List<String> items = Arrays.asList("apple", "banana", "cherry");
String result = String.join(", ", items);
// Or use Streams
String result = IntStream.range(0, 1000)
.mapToObj(String::valueOf)
.collect(Collectors.joining(","));
✅ 単純な連結 - + を使用しても問題ありません:
// OK for simple cases (compiler optimizes)
String fullName = firstName + " " + lastName;
String message = "Hello, " + name + "!";
// Not OK in loops
for (String item : items) {
result = result + item; // BAD!
}
Enum の使用
ルール: 固定された定数の集合には enum を使用します。enum にはフィールド、メソッド、コンストラクターを定義できます。
✅ 基本的な Enum:
public enum OrderStatus {
PENDING,
PROCESSING,
SHIPPED,
DELIVERED,
CANCELLED
}
// Usage
Order order = new Order();
order.setStatus(OrderStatus.PENDING);
if (order.getStatus() == OrderStatus.DELIVERED) {
// Process delivery
}
✅ フィールドとメソッドを持つ Enum:
public enum PaymentMethod {
CREDIT_CARD("Credit Card", 2.9),
DEBIT_CARD("Debit Card", 1.5),
PAYPAL("PayPal", 3.5),
BITCOIN("Bitcoin", 1.0);
private final String displayName;
private final double transactionFeePercent;
PaymentMethod(String displayName, double transactionFeePercent) {
this.displayName = displayName;
this.transactionFeePercent = transactionFeePercent;
}
public String getDisplayName() {
return displayName;
}
public double calculateFee(double amount) {
return amount * (transactionFeePercent / 100);
}
public double calculateTotal(double amount) {
return amount + calculateFee(amount);
}
}
// Usage
PaymentMethod method = PaymentMethod.CREDIT_CARD;
double total = method.calculateTotal(100.0); // 102.90
System.out.println("Paying with: " + method.getDisplayName());
✅ 抽象メソッドを持つ Enum(ストラテジーパターン):
public enum Operation {
PLUS {
@Override
public double apply(double x, double y) {
return x + y;
}
},
MINUS {
@Override
public double apply(double x, double y) {
return x - y;
}
},
MULTIPLY {
@Override
public double apply(double x, double y) {
return x * y;
}
},
DIVIDE {
@Override
public double apply(double x, double y) {
if (y == 0) throw new ArithmeticException("Division by zero");
return x / y;
}
};
public abstract double apply(double x, double y);
}
// Usage
double result = Operation.PLUS.apply(5, 3); // 8.0
例外処理
チェック例外と非チェック例外
ルール: 回復可能な状況にはチェック例外を、プログラミングエラーには非チェック例外を使用します。
チェック例外:
Exceptionを継承します(RuntimeExceptionではありません)- メソッドシグネチャで宣言するか、捕捉する必要があります
- 呼び出し側が妥当に対処できる状況に使用します
非チェック例外:
RuntimeExceptionを継承します- 宣言や捕捉は不要です
- プログラミングエラーに使用します
✅ それぞれを使う場面:
// Checked exception - caller can handle
public User findUserById(Long id) throws UserNotFoundException {
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException("User not found: " + id));
}
// Unchecked exception - programming error
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
this.age = age;
}
// Checked exception - I/O operation
public String readFile(String path) throws IOException {
return Files.readString(Paths.get(path));
}
// Unchecked exception - null argument (programming error)
public void processOrder(Order order) {
Objects.requireNonNull(order, "Order cannot be null");
// Process order
}
捕捉するか、送出するか
ルール: 例外を意味のある形で処理できる場合にのみ捕捉します。それ以外の場合は、そのまま伝播させます。
❌ 悪い例 - 捕捉して再送出する:
public void processData(String data) throws DataProcessingException {
try {
// Process data
} catch (JsonParseException e) {
throw new DataProcessingException(e); // Unnecessary try-catch
}
}
// Better: Let it propagate
public void processData(String data) throws JsonParseException {
// Process data
}
✅ 良い例 - 対処できる場合に捕捉する:
public void processDataWithRetry(String data) {
int maxAttempts = 3;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
processData(data);
return; // Success
} catch (TransientException e) {
if (attempt == maxAttempts) {
log.error("Failed after {} attempts", maxAttempts, e);
throw new DataProcessingException("Processing failed", e);
}
log.warn("Attempt {} failed, retrying...", attempt);
sleep(1000 * attempt); // Exponential backoff
}
}
}
カスタム例外の設計
✅ 適切に設計されたカスタム例外:
public class InsufficientFundsException extends Exception {
private final double requestedAmount;
private final double availableBalance;
public InsufficientFundsException(double requestedAmount, double availableBalance) {
super(String.format("Insufficient funds: requested %.2f, available %.2f",
requestedAmount, availableBalance));
this.requestedAmount = requestedAmount;
this.availableBalance = availableBalance;
}
public double getRequestedAmount() {
return requestedAmount;
}
public double getAvailableBalance() {
return availableBalance;
}
public double getShortfall() {
return requestedAmount - availableBalance;
}
}
// Usage
try {
account.withdraw(500);
} catch (InsufficientFundsException e) {
log.error("Withdrawal failed: {}", e.getMessage());
notifyUser(String.format("You need $%.2f more", e.getShortfall()));
}
例外のログ記録
✅ 例外ログ記録のベストプラクティス:
public void processOrder(Order order) {
try {
validateOrder(order);
saveOrder(order);
sendConfirmation(order);
} catch (ValidationException e) {
// Log with context
log.error("Order validation failed for order {}: {}",
order.getId(), e.getMessage(), e);
throw e;
} catch (DataAccessException e) {
// Log with different level based on recoverability
log.error("Failed to save order {}", order.getId(), e);
throw new OrderProcessingException("Failed to save order", e);
} catch (EmailException e) {
// Non-critical error - log warning
log.warn("Failed to send confirmation email for order {}",
order.getId(), e);
// Don't rethrow - order was saved successfully
}
}
例外を決して握りつぶさない
❌ 悪い例 - 例外を握りつぶす:
try {
riskyOperation();
} catch (Exception e) {
// Silent failure - NEVER DO THIS!
}
try {
closeResource();
} catch (Exception e) {
e.printStackTrace(); // Insufficient - use logging!
}
✅ 良い例 - 適切な例外処理:
try {
riskyOperation();
} catch (Exception e) {
log.error("Operation failed", e);
throw new ApplicationException("Failed to perform operation", e);
}
// Or if truly acceptable to ignore
try {
closeResource();
} catch (IOException e) {
log.warn("Failed to close resource (non-critical)", e);
// OK to continue without rethrowing in cleanup scenarios
}
コレクションとジェネリクス
適切なコレクションの選択
コレクション選択ガイド:
// List - Ordered collection, allows duplicates
// Use ArrayList for random access, LinkedList for frequent insertions/deletions
List<String> names = new ArrayList<>();
List<Task> taskQueue = new LinkedList<>();
// Set - No duplicates, no guaranteed order
// Use HashSet for general use, TreeSet for sorted, LinkedHashSet for insertion order
Set<String> uniqueEmails = new HashSet<>();
Set<Integer> sortedNumbers = new TreeSet<>();
Set<String> insertionOrderSet = new LinkedHashSet<>();
// Map - Key-value pairs, no duplicate keys
// Use HashMap for general use, TreeMap for sorted keys, LinkedHashMap for insertion order
Map<Long, User> userCache = new HashMap<>();
Map<String, Integer> sortedMap = new TreeMap<>();
Map<String, String> orderedMap = new LinkedHashMap<>();
// Queue - FIFO operations
// Use LinkedList or ArrayDeque for general queue
Queue<Task> taskQueue = new LinkedList<>();
Deque<String> deque = new ArrayDeque<>();
// Stack operations - Use Deque instead of Stack class
Deque<String> stack = new ArrayDeque<>();
stack.push("item");
String item = stack.pop();
パフォーマンス特性:
// ArrayList
// - Get by index: O(1)
// - Add at end: O(1) amortized
// - Insert/remove at position: O(n)
// - Search: O(n)
// LinkedList
// - Get by index: O(n)
// - Add/remove at beginning/end: O(1)
// - Insert/remove at position: O(n)
// - Search: O(n)
// HashSet/HashMap
// - Add/remove/contains: O(1) average
// - Iteration: O(capacity + size)
// TreeSet/TreeMap
// - Add/remove/contains: O(log n)
// - Iteration in sorted order: O(n)
不変コレクション
✅ 不変コレクションの作成:
// Java 9+ factory methods (preferred)
List<String> immutableList = List.of("a", "b", "c");
Set<String> immutableSet = Set.of("x", "y", "z");
Map<String, Integer> immutableMap = Map.of(
"one", 1,
"two", 2,
"three", 3
);
// For more than 10 entries in Map
Map<String, Integer> largeMap = Map.ofEntries(
Map.entry("key1", 1),
Map.entry("key2", 2),
Map.entry("key3", 3)
);
// Pre-Java 9 - Collections.unmodifiableXxx
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
List<String> immutableList = Collections.unmodifiableList(list);
// Guava (if available)
ImmutableList<String> immutableList = ImmutableList.of("a", "b", "c");
ImmutableSet<String> immutableSet = ImmutableSet.of("x", "y", "z");
ImmutableMap<String, Integer> immutableMap = ImmutableMap.of("one", 1, "two", 2);
ジェネリック型の安全性
✅ 適切なジェネリクスの使用:
// Generic class
public class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
// Multiple type parameters
public class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
// Bounded type parameters
public class NumberBox<T extends Number> {
private T number;
public void set(T number) {
this.number = number;
}
public double getDoubleValue() {
return number.doubleValue(); // Can call Number methods
}
}
// Generic method
public <T> List<T> createList(T... elements) {
return Arrays.asList(elements);
}
// Wildcard usage
public void processList(List<? extends Number> numbers) {
for (Number num : numbers) {
System.out.println(num.doubleValue());
}
}
public void addToList(List<? super Integer> list) {
list.add(42); // Can add Integer
}
ダイヤモンド演算子の使用
✅ ダイヤモンド演算子を使用する(Java 7 以降):
// Before Java 7
Map<String, List<String>> map = new HashMap<String, List<String>>();
// Java 7+ with diamond operator
Map<String, List<String>> map = new HashMap<>();
// Works with anonymous classes (Java 9+)
List<String> list = new ArrayList<>() {
{
add("item");
}
};
並行処理
スレッドセーフ性
ルール: 最初からスレッドセーフ性を考慮して設計します。別途記載がない限り、マルチスレッドからアクセスされるものと想定します。
✅ スレッドセーフなパターン:
// 1. Immutable objects (inherently thread-safe)
public final class ImmutableUser {
private final String name;
private final String email;
public ImmutableUser(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() { return name; }
public String getEmail() { return email; }
}
// 2. Synchronized methods
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
// 3. Concurrent collections
private final Map<String, User> userCache = new ConcurrentHashMap<>();
private final List<String> logMessages = new CopyOnWriteArrayList<>();
// 4. Atomic variables
private final AtomicInteger counter = new AtomicInteger(0);
public void incrementCounter() {
counter.incrementAndGet();
}
public int getCounter() {
return counter.get();
}
// 5. ThreadLocal for thread-specific data
private static final ThreadLocal<SimpleDateFormat> dateFormat =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
public String formatDate(Date date) {
return dateFormat.get().format(date);
}
ExecutorService の使用
✅ ExecutorService の使用:
// Fixed thread pool
ExecutorService executor = Executors.newFixedThreadPool(10);
// Submit tasks
for (int i = 0; i < 100; i++) {
final int taskId = i;
executor.submit(() -> {
processTask(taskId);
});
}
// Shutdown gracefully
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
// Try-with-resources (Java 19+)
try (ExecutorService executor = Executors.newFixedThreadPool(10)) {
// Submit tasks
} // Auto-shutdown
// Custom thread pool for better control
ExecutorService customExecutor = new ThreadPoolExecutor(
5, // core pool size
10, // maximum pool size
60L, TimeUnit.SECONDS, // keep alive time
new LinkedBlockingQueue<>(100), // work queue
new ThreadPoolExecutor.CallerRunsPolicy() // rejection policy
);
CompletableFuture のパターン
✅ CompletableFuture による非同期プログラミング:
// Simple async task
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Long-running task
return fetchDataFromApi();
});
// Chain operations
CompletableFuture<UserDto> userFuture = CompletableFuture
.supplyAsync(() -> fetchUserFromDatabase(userId))
.thenApply(user -> mapToDto(user))
.thenApply(dto -> enrichWithAdditionalData(dto));
// Combine multiple futures
CompletableFuture<User> userFuture = fetchUserAsync(userId);
CompletableFuture<List<Order>> ordersFuture = fetchOrdersAsync(userId);
CompletableFuture<UserWithOrders> combined = userFuture
.thenCombine(ordersFuture, (user, orders) ->
new UserWithOrders(user, orders));
// Handle errors
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> riskyOperation())
.exceptionally(ex -> {
log.error("Operation failed", ex);
return "default value";
});
// Multiple async operations
List<CompletableFuture<String>> futures = ids.stream()
.map(id -> CompletableFuture.supplyAsync(() -> fetchData(id)))
.collect(Collectors.toList());
// Wait for all to complete
CompletableFuture<Void> allOf = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0]));
allOf.thenRun(() -> {
List<String> results = futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
processResults(results);
});
デッドロックの回避
✅ デッドロックの防止:
// 1. Always acquire locks in the same order
public class BankAccount {
private final Object lock = new Object();
private double balance;
public static void transfer(BankAccount from, BankAccount to, double amount) {
// Always lock accounts in consistent order (by hashCode)
BankAccount first = from.hashCode() < to.hashCode() ? from : to;
BankAccount second = from.hashCode() < to.hashCode() ? to : from;
synchronized (first.lock) {
synchronized (second.lock) {
if (from == first) {
from.withdraw(amount);
to.deposit(amount);
} else {
from.deposit(amount);
to.withdraw(amount);
}
}
}
}
}
// 2. Use tryLock with timeout
Lock lock1 = new ReentrantLock();
Lock lock2 = new ReentrantLock();
try {
if (lock1.tryLock(1, TimeUnit.SECONDS)) {
try {
if (lock2.tryLock(1, TimeUnit.SECONDS)) {
try {
// Critical section
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// 3. Use higher-level concurrency utilities
ConcurrentHashMap<String, Account> accounts = new ConcurrentHashMap<>();
accounts.compute("account1", (key, account) -> {
account.withdraw(100);
return account;
});
アトミッククラス
✅ アトミッククラスの使用:
public class Statistics {
private final AtomicLong totalRequests = new AtomicLong(0);
private final AtomicLong successfulRequests = new AtomicLong(0);
private final AtomicLong failedRequests = new AtomicLong(0);
public void recordSuccess() {
totalRequests.incrementAndGet();
successfulRequests.incrementAndGet();
}
public void recordFailure() {
totalRequests.incrementAndGet();
failedRequests.incrementAndGet();
}
public double getSuccessRate() {
long total = totalRequests.get();
if (total == 0) return 0.0;
return (double) successfulRequests.get() / total;
}
// Atomic update with compareAndSet
private final AtomicReference<Config> config =
new AtomicReference<>(new Config());
public void updateConfig(Config newConfig) {
Config current;
do {
current = config.get();
} while (!config.compareAndSet(current, newConfig));
}
}
テスト(TDD)
JUnit 5 による単体テスト
✅ JUnit 5 のベストプラクティス:
@DisplayName("User Service Tests")
class UserServiceTest {
private UserService userService;
private UserRepository userRepository;
private PasswordEncoder passwordEncoder;
@BeforeEach
void setUp() {
userRepository = mock(UserRepository.class);
passwordEncoder = mock(PasswordEncoder.class);
userService = new UserService(userRepository, passwordEncoder);
}
@Test
@DisplayName("Should create user with valid data")
void shouldCreateUserWithValidData() {
// Arrange
String email = "[email protected]";
String password = "SecurePass123!";
String encodedPassword = "encoded_password";
when(passwordEncoder.encode(password)).thenReturn(encodedPassword);
when(userRepository.existsByEmail(email)).thenReturn(false);
// Act
User user = userService.createUser(email, password);
// Assert
assertNotNull(user);
assertEquals(email, user.getEmail());
assertEquals(encodedPassword, user.getPasswordHash());
verify(userRepository).save(any(User.class));
}
@Test
@DisplayName("Should throw exception when email already exists")
void shouldThrowExceptionWhenEmailExists() {
// Arrange
String email = "[email protected]";
when(userRepository.existsByEmail(email)).thenReturn(true);
// Act & Assert
assertThrows(DuplicateEmailException.class, () ->
userService.createUser(email, "password"));
verify(userRepository, never()).save(any());
}
@ParameterizedTest
@ValueSource(strings = {"", " ", "invalid-email", "@example.com"})
@DisplayName("Should throw exception for invalid email formats")
void shouldThrowExceptionForInvalidEmail(String invalidEmail) {
assertThrows(ValidationException.class, () ->
userService.createUser(invalidEmail, "password"));
}
@ParameterizedTest
@CsvSource({
"[email protected], short, 'Password too short'",
"[email protected], nodigits, 'Password must contain digits'",
"invalid, ValidPass123!, 'Invalid email format'"
})
@DisplayName("Should validate user input correctly")
void shouldValidateUserInput(String email, String password, String expectedError) {
ValidationException exception = assertThrows(ValidationException.class, () ->
userService.createUser(email, password));
assertTrue(exception.getMessage().contains(expectedError));
}
@Test
@DisplayName("Should handle repository exception gracefully")
void shouldHandleRepositoryException() {
// Arrange
when(userRepository.save(any())).thenThrow(new DataAccessException("DB error"));
// Act & Assert
assertThrows(UserCreationException.class, () ->
userService.createUser("[email protected]", "password"));
}
@Nested
@DisplayName("User Authentication Tests")
class UserAuthenticationTests {
@Test
@DisplayName("Should authenticate user with correct password")
void shouldAuthenticateWithCorrectPassword() {
// Arrange
User user = new User("[email protected]", "encoded_pass");
when(userRepository.findByEmail("[email protected]"))
.thenReturn(Optional.of(user));
when(passwordEncoder.matches("password", "encoded_pass"))
.thenReturn(true);
// Act
boolean authenticated = userService.authenticate("[email protected]", "password");
// Assert
assertTrue(authenticated);
}
@Test
@DisplayName("Should reject authentication with wrong password")
void shouldRejectWithWrongPassword() {
// Arrange
User user = new User("[email protected]", "encoded_pass");
when(userRepository.findByEmail("[email protected]"))
.thenReturn(Optional.of(user));
when(passwordEncoder.matches("wrong", "encoded_pass"))
.thenReturn(false);
// Act
boolean authenticated = userService.authenticate("[email protected]", "wrong");
// Assert
assertFalse(authenticated);
}
}
}
Mockito によるモック化
✅ Mockito のベストプラクティス:
public class OrderServiceTest {
@Mock
private OrderRepository orderRepository;
@Mock
private PaymentService paymentService;
@Mock
private EmailService emailService;
@InjectMocks
private OrderService orderService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void shouldProcessOrderSuccessfully() {
// Arrange
Order order = new Order();
order.setId(1L);
order.setTotal(100.0);
when(paymentService.charge(any(), anyDouble())).thenReturn(true);
when(orderRepository.save(any(Order.class))).thenReturn(order);
// Act
orderService.processOrder(order);
// Assert
verify(paymentService).charge(order, 100.0);
verify(orderRepository).save(order);
verify(emailService).sendConfirmation(order);
assertEquals(OrderStatus.COMPLETED, order.getStatus());
}
@Test
void shouldHandlePaymentFailure() {
// Arrange
Order order = new Order();
when(paymentService.charge(any(), anyDouble())).thenReturn(false);
// Act & Assert
assertThrows(PaymentFailedException.class, () ->
orderService.processOrder(order));
verify(emailService, never()).sendConfirmation(any());
assertEquals(OrderStatus.PAYMENT_FAILED, order.getStatus());
}
@Test
void shouldRetryOnTransientFailure() {
// Arrange
Order order = new Order();
// First two calls fail, third succeeds
when(paymentService.charge(any(), anyDouble()))
.thenThrow(new TransientException())
.thenThrow(new TransientException())
.thenReturn(true);
// Act
orderService.processOrderWithRetry(order);
// Assert
verify(paymentService, times(3)).charge(any(), anyDouble());
}
@Test
void shouldCaptureArgumentValues() {
// Arrange
ArgumentCaptor<Order> orderCaptor = ArgumentCaptor.forClass(Order.class);
Order order = new Order();
order.setTotal(100.0);
// Act
orderService.processOrder(order);
// Assert
verify(orderRepository).save(orderCaptor.capture());
Order savedOrder = orderCaptor.getValue();
assertEquals(OrderStatus.COMPLETED, savedOrder.getStatus());
assertNotNull(savedOrder.getProcessedAt());
}
}
テストの構成
パッケージ構造:
src/
├── main/
│ └── java/
│ └── com/example/
│ ├── model/
│ │ └── User.java
│ └── service/
│ └── UserService.java
└── test/
└── java/
└── com/example/
├── model/
│ └── UserTest.java
└── service/
└── UserServiceTest.java
AAA パターン(準備・実行・検証)
✅ 明確なテスト構成:
@Test
void shouldCalculateDiscountCorrectly() {
// Arrange - Set up test data and expectations
Product product = new Product("Laptop", 1000.0);
Discount discount = new Discount(10); // 10%
PriceCalculator calculator = new PriceCalculator();
// Act - Execute the behavior being tested
double finalPrice = calculator.calculateFinalPrice(product, discount);
// Assert - Verify the expected outcome
assertEquals(900.0, finalPrice, 0.01);
}
プライベートメソッドのテスト
ルール: プライベートメソッドを直接テストしないでください。パブリックメソッドを通じてテストします。
❌ 悪い例:
@Test
void testPrivateMethod() {
// Using reflection to test private method - BAD!
Method method = UserService.class.getDeclaredMethod("validateEmail", String.class);
method.setAccessible(true);
boolean result = (boolean) method.invoke(userService, "[email protected]");
assertTrue(result);
}
✅ 良い例:
@Test
void shouldRejectInvalidEmailDuringUserCreation() {
// Test private validateEmail() through public createUser()
assertThrows(ValidationException.class, () ->
userService.createUser("invalid-email", "password"));
}
テストカバレッジの目標
推奨カバレッジ目標:
- 重要なビジネスロジック:100%
- サービス層:90~100%
- コントローラー層:80~90%
- ユーティリティクラス:90~100%
- プロジェクト全体:最低80%
ツール:
- カバレッジレポートには JaCoCo
- コード品質分析には SonarQube
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.10</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>coverage-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>PACKAGE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.80</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
コードの構成
パッケージ構造
✅ レイヤードアーキテクチャ:
com.example.myapp/
├── controller/ # REST controllers
│ ├── UserController.java
│ └── OrderController.java
├── service/ # Business logic
│ ├── UserService.java
│ └── OrderService.java
├── repository/ # Data access
│ ├── UserRepository.java
│ └── OrderRepository.java
├── model/ # Domain models
│ ├── User.java
│ └── Order.java
├── dto/ # Data transfer objects
│ ├── UserDto.java
│ └── OrderDto.java
├── exception/ # Custom exceptions
│ ├── UserNotFoundException.java
│ └── ValidationException.java
├── config/ # Configuration classes
│ ├── SecurityConfig.java
│ └── DatabaseConfig.java
└── util/ # Utility classes
├── DateUtils.java
└── StringUtils.java
✅ 機能ベースの構成(大規模アプリ向け):
com.example.myapp/
├── user/
│ ├── User.java
│ ├── UserController.java
│ ├── UserService.java
│ ├── UserRepository.java
│ └── UserDto.java
├── order/
│ ├── Order.java
│ ├── OrderController.java
│ ├── OrderService.java
│ ├── OrderRepository.java
│ └── OrderDto.java
└── common/
├── exception/
├── config/
└── util/
クラスの命名規則
// Controllers: Noun + Controller
public class UserController { }
public class OrderController { }
// Services: Noun + Service
public class UserService { }
public class PaymentService { }
// Repositories: Noun + Repository
public class UserRepository { }
public class OrderRepository { }
// DTOs: Noun + Dto
public class UserDto { }
public class CreateOrderDto { }
// Exceptions: Description + Exception
public class UserNotFoundException extends RuntimeException { }
public class InvalidEmailException extends ValidationException { }
// Utilities: Plural noun + Utils
public class StringUtils { }
public class DateUtils { }
// Interfaces: Adjective or Noun
public interface Serializable { }
public interface PaymentProcessor { }
メソッドの命名規則
// Getters/Setters
public String getName() { }
public void setName(String name) { }
// Boolean getters: is/has/can
public boolean isActive() { }
public boolean hasPermission() { }
public boolean canExecute() { }
// Actions: verb + noun
public void createUser() { }
public void processPayment() { }
public void calculateTotal() { }
// Queries: get/find/search + noun
public User getUser(Long id) { }
public List<User> findActiveUsers() { }
public List<Order> searchByDate(LocalDate date) { }
// Validators: validate + noun
public void validateEmail(String email) { }
public boolean isValidPassword(String password) { }
定数と設定
✅ 定数:
public class ApplicationConstants {
// Public constants: public static final
public static final int MAX_RETRY_ATTEMPTS = 3;
public static final String DEFAULT_ENCODING = "UTF-8";
public static final Duration CONNECTION_TIMEOUT = Duration.ofSeconds(30);
// Private constructor to prevent instantiation
private ApplicationConstants() {
throw new AssertionError("Cannot instantiate constants class");
}
}
// Or use enums for related constants
public enum HttpStatus {
OK(200, "OK"),
NOT_FOUND(404, "Not Found"),
INTERNAL_SERVER_ERROR(500, "Internal Server Error");
private final int code;
private final String message;
HttpStatus(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() { return code; }
public String getMessage() { return message; }
}
ビルダーパターン
✅ 複雑なオブジェクト向けのビルダー:
public class User {
private final String email;
private final String firstName;
private final String lastName;
private final LocalDate dateOfBirth;
private final String phoneNumber;
private final Address address;
private User(Builder builder) {
this.email = builder.email;
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.dateOfBirth = builder.dateOfBirth;
this.phoneNumber = builder.phoneNumber;
this.address = builder.address;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String email;
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private String phoneNumber;
private Address address;
public Builder email(String email) {
this.email = email;
return this;
}
public Builder firstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder lastName(String lastName) {
this.lastName = lastName;
return this;
}
public Builder dateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
return this;
}
public Builder phoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public Builder address(Address address) {
this.address = address;
return this;
}
public User build() {
validateRequired();
return new User(this);
}
private void validateRequired() {
if (email == null) throw new IllegalStateException("Email is required");
if (firstName == null) throw new IllegalStateException("First name is required");
}
}
// Getters
public String getEmail() { return email; }
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public LocalDate getDateOfBirth() { return dateOfBirth; }
public String getPhoneNumber() { return phoneNumber; }
public Address getAddress() { return address; }
}
// Usage
User user = User.builder()
.email("[email protected]")
.firstName("John")
.lastName("Doe")
.dateOfBirth(LocalDate.of(1990, 1, 1))
.phoneNumber("555-1234")
.build();
ファクトリーパターン
✅ オブジェクト生成向けのファクトリー:
public interface PaymentProcessor {
void processPayment(double amount);
}
public class CreditCardProcessor implements PaymentProcessor {
@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment: $" + amount);
}
}
public class PayPalProcessor implements PaymentProcessor {
@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment: $" + amount);
}
}
public class PaymentProcessorFactory {
public static PaymentProcessor create(PaymentMethod method) {
switch (method) {
case CREDIT_CARD:
return new CreditCardProcessor();
case PAYPAL:
return new PayPalProcessor();
case BITCOIN:
return new BitcoinProcessor();
default:
throw new IllegalArgumentException("Unknown payment method: " + method);
}
}
}
// Usage
PaymentProcessor processor = PaymentProcessorFactory.create(PaymentMethod.CREDIT_CARD);
processor.processPayment(100.0);
パフォーマンス
文字列の最適化
✅ 文字列のパフォーマンスに関するヒント:
// Use String.format() sparingly (it's slow)
// OK for occasional use
String message = String.format("User %s logged in at %s", username, timestamp);
// For frequent formatting, use StringBuilder
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
builder.append("Item ").append(i).append("\n");
}
String result = builder.toString();
// Use String.join() for collections
List<String> items = Arrays.asList("apple", "banana", "cherry");
String joined = String.join(", ", items);
// Avoid string concatenation in loops
String result = "";
for (String item : items) {
result += item; // BAD - creates many String objects
}
// Use StringBuilder instead
StringBuilder result = new StringBuilder();
for (String item : items) {
result.append(item);
}
// String interning for frequently used strings
String s1 = new String("hello").intern();
String s2 = "hello";
assert s1 == s2; // Same reference
コレクションのパフォーマンス
// ArrayList vs LinkedList
List<String> arrayList = new ArrayList<>(); // Fast random access O(1)
List<String> linkedList = new LinkedList<>(); // Fast insertion/deletion at ends O(1)
// HashSet vs TreeSet
Set<String> hashSet = new HashSet<>(); // O(1) add/contains, no order
Set<String> treeSet = new TreeSet<>(); // O(log n) add/contains, sorted
// HashMap vs TreeMap vs LinkedHashMap
Map<String, Integer> hashMap = new HashMap<>(); // O(1) get/put, no order
Map<String, Integer> treeMap = new TreeMap<>(); // O(log n) get/put, sorted by key
Map<String, Integer> linkedHashMap = new LinkedHashMap<>(); // O(1) get/put, insertion order
// Pre-size collections when size is known
List<String> list = new ArrayList<>(1000); // Avoids resizing
Map<String, String> map = new HashMap<>(1000);
// Use EnumSet for enum values
Set<DayOfWeek> weekdays = EnumSet.of(
DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY, DayOfWeek.FRIDAY
);
Stream とループのパフォーマンス
ルール: Stream は読みやすい一方、小規模なコレクションではオーバーヘッドが発生する場合があります。重要な処理経路ではパフォーマンスを測定してください。
// For small collections (<100 items), loops may be faster
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Loop (slightly faster for small collections)
int sum = 0;
for (int num : numbers) {
sum += num;
}
// Stream (more readable, negligible overhead)
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
// For large collections or parallel processing, streams shine
List<Integer> largeList = IntStream.range(0, 1_000_000)
.boxed()
.collect(Collectors.toList());
// Parallel stream for CPU-intensive operations
int sum = largeList.parallelStream()
.mapToInt(Integer::intValue)
.sum();
メモリ管理
✅ メモリに関するベストプラクティス:
// Close resources to free memory
try (FileInputStream fis = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(fis)) {
// Use streams
} // Automatically closed
// Avoid memory leaks with listeners
public class EventSource {
private final List<EventListener> listeners = new ArrayList<>();
public void addListener(EventListener listener) {
listeners.add(listener);
}
public void removeListener(EventListener listener) {
listeners.remove(listener); // Important: allow garbage collection
}
}
// Use weak references for caches
Map<String, WeakReference<User>> cache = new WeakHashMap<>();
// Clear collections when done
List<LargeObject> objects = new ArrayList<>();
// ... use objects
objects.clear(); // Allow garbage collection
// Avoid string concatenation creating many objects
String result = "Hello" + " " + "World"; // OK - compiler optimizes
String result = str1 + str2 + str3; // OK - compiler uses StringBuilder
// Not OK in loops - use StringBuilder explicitly
for (String item : items) {
result = result + item; // Creates new String each iteration
}
よくあるアンチパターン
巨大なオブジェクト
❌ アンチパターン - 巨大なオブジェクト:
// One class doing everything - AVOID!
public class OrderManager {
// User management
public void createUser() { }
public void deleteUser() { }
// Order processing
public void createOrder() { }
public void processOrder() { }
// Payment processing
public void processPayment() { }
// Email sending
public void sendConfirmation() { }
// Reporting
public void generateReport() { }
// Database operations
public void saveToDatabase() { }
// Logging
public void logActivity() { }
// 50+ more methods...
}
✅ 解決策 - 単一責任:
public class UserService {
public void createUser() { }
public void deleteUser() { }
}
public class OrderService {
public void createOrder() { }
public void processOrder() { }
}
public class PaymentService {
public void processPayment() { }
}
public class EmailService {
public void sendConfirmation() { }
}
プリミティブ型への執着
❌ アンチパターン - プリミティブ型への執着:
public class Order {
private double price; // What currency?
private double weight; // What unit?
private String phoneNumber; // No validation!
private String email; // No validation!
}
✅ 解決策 - 値オブジェクト:
public class Money {
private final double amount;
private final Currency currency;
public Money(double amount, Currency currency) {
this.amount = amount;
this.currency = currency;
}
// Methods for money operations
}
public class Weight {
private final double value;
private final WeightUnit unit;
public Weight(double value, WeightUnit unit) {
this.value = value;
this.unit = unit;
}
}
public class Email {
private final String value;
public Email(String value) {
if (!isValid(value)) {
throw new IllegalArgumentException("Invalid email");
}
this.value = value;
}
private boolean isValid(String email) {
return email.contains("@"); // Simplified
}
}
public class Order {
private Money price;
private Weight weight;
private Email customerEmail;
}
長いパラメーターリスト
❌ アンチパターン - 長いパラメーターリスト:
public void createUser(
String firstName,
String lastName,
String email,
String phoneNumber,
String addressLine1,
String addressLine2,
String city,
String state,
String zipCode,
String country
) {
// Too many parameters!
}
✅ 解決策 - パラメーターオブジェクト:
public class UserRegistration {
private final String firstName;
private final String lastName;
private final String email;
private final String phoneNumber;
private final Address address;
// Constructor, getters, builder
}
public class Address {
private final String line1;
private final String line2;
private final String city;
private final String state;
private final String zipCode;
private final String country;
// Constructor, getters, builder
}
public void createUser(UserRegistration registration) {
// Clean method signature
}
マジックナンバー
❌ アンチパターン - マジックナンバー:
public void processOrder(Order order) {
if (order.getTotal() > 100) { // What is 100?
applyDiscount(order, 0.1); // What is 0.1?
}
if (order.getItems().size() > 5) { // What is 5?
// Free shipping
}
}
✅ 解決策 - 名前付き定数:
private static final double FREE_SHIPPING_THRESHOLD = 100.0;
private static final double BULK_DISCOUNT_RATE = 0.1;
private static final int BULK_ORDER_ITEM_COUNT = 5;
public void processOrder(Order order) {
if (order.getTotal() > FREE_SHIPPING_THRESHOLD) {
applyDiscount(order, BULK_DISCOUNT_RATE);
}
if (order.getItems().size() > BULK_ORDER_ITEM_COUNT) {
// Free shipping
}
}
ネストされた条件分岐
❌ アンチパターン - 深くネストされた条件分岐:
public void processPayment(Order order) {
if (order != null) {
if (order.getCustomer() != null) {
if (order.getCustomer().hasPaymentMethod()) {
if (order.getTotal() > 0) {
if (inventory.isAvailable(order)) {
// Process payment
} else {
throw new InsufficientInventoryException();
}
} else {
throw new InvalidAmountException();
}
} else {
throw new NoPaymentMethodException();
}
} else {
throw new NoCustomerException();
}
} else {
throw new NullOrderException();
}
}
✅ 解決策 - ガード節:
public void processPayment(Order order) {
// Guard clauses - fail fast
if (order == null) {
throw new NullOrderException();
}
if (order.getCustomer() == null) {
throw new NoCustomerException();
}
if (!order.getCustomer().hasPaymentMethod()) {
throw new NoPaymentMethodException();
}
if (order.getTotal() <= 0) {
throw new InvalidAmountException();
}
if (!inventory.isAvailable(order)) {
throw new InsufficientInventoryException();
}
// Happy path at the end
processPaymentInternal(order);
}
null の返却
❌ アンチパターン - null の返却:
public User findUser(Long id) {
// May return null
return database.find(id);
}
// Caller must remember null check
User user = findUser(123L);
if (user != null) {
String email = user.getEmail(); // NullPointerException risk
}
✅ 解決策 - Optional を返す:
public Optional<User> findUser(Long id) {
return Optional.ofNullable(database.find(id));
}
// Caller forced to handle absence
Optional<User> userOpt = findUser(123L);
String email = userOpt
.map(User::getEmail)
.orElse("[email protected]");
リソースを閉じない
❌ アンチパターン - リソースリーク:
public String readFile(String path) {
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
return br.readLine(); // Resources never closed!
}
✅ 解決策 - Try-With-Resources:
public String readFile(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
return reader.readLine();
} // Automatically closed
}
チェックリスト
コードレビューでこのチェックリストを使用し、Java コードの品質を確認してください。
SOLID 原則
- 各クラスに、単一かつ明確に定義された責任がある
- クラスは拡張に開かれ、変更に閉じている
- サブクラスは基底クラスと置き換え可能である
- インターフェースは小さく、目的が明確である
- 依存関係が逆転している(抽象に依存する)
DRY 原則
- 明らかなコードの重複がない
- 共通ロジックがユーティリティメソッド/クラスに抽出されている
- 適切な箇所でジェネリクスを使用している
クリーンコード
- クラス、メソッド、変数の名前に意味がある
- メソッドが小さい(理想的には 5~20 行)
- コメントは「何を」ではなく「なぜ」を説明している
- 適切な例外処理が行われている(例外を握りつぶしていない)
- コードが適切に整理されている
Java 固有
- 値が存在しない場合に null ではなく Optional を使用している
- 継承よりコンポジションを優先している
- 適切な箇所で不変性を使用している(final フィールド/クラス)
- コレクション操作に Stream API を使用している
- ラムダ式とメソッド参照を使用している
- AutoCloseable リソースに try-with-resources を使用している
- ループ内での文字列連結に StringBuilder を使用している
- 固定された定数の集合に enum を使用している
例外処理
- 適切な例外の種類を選択している(チェック例外/非チェック例外)
- 処理できる場合にのみ例外を捕捉している
- カスタム例外が適切に設計されている
- コンテキスト情報とともに例外をログに記録している
- 空の catch ブロックがない
コレクション
- 適切なコレクション型を選択している
- 適切な箇所で不変コレクションを使用している
- ジェネリック型のパラメーターを指定している
- ダイヤモンド演算子を使用している(Java 7 以降)
並行処理
- スレッドセーフ性を考慮している
- 適切な同期メカニズムを使用している
- スレッドプールに ExecutorService を使用している
- 非同期処理に CompletableFuture を使用している
- デッドロックの防止を考慮している
- 単純なアトミック操作にアトミッククラスを使用している
テスト
- ビジネスロジックの単体テストがある
- テストが AAA パターンに従っている
- モックを適切に使用している
- テストが分離され、互いに独立している
- テストカバレッジが基準を満たしている(80% 以上)
コードの整理
- パッケージ構成が適切である
- 命名規則に従っている
- 定数が適切に定義されている
- Builder/Factory パターンを適切に使用している
パフォーマンス
- 文字列操作が最適化されている
- 用途に合ったコレクション型を使用している
- リソースを適切に管理している
- 明らかなパフォーマンス上の問題がない
アンチパターン
- God オブジェクトがない
- プリミティブ型への固執がない
- 長いパラメーターリストがない
- マジックナンバーがない
- 深くネストされた条件分岐がない
- Optional が適切な箇所で null を返していない
- リソースリークがない
関連スキル
- uncle-duke-java:このスキルを参考にする Java コードレビューエージェント
参考資料
Java ドキュメント
Spring Framework
Best Practices
Testing
Tools
Version: 1.0 Last Updated: 2025-12-24 Maintainer: Development Team