Language Początkujący

Add static utility methods directly to interfaces instead of separate utility classes.

✕ Java 7
// Separate utility class needed
public class ValidatorUtils {
    public static boolean isBlank(
        String s) {
        return s == null ||
               s.trim().isEmpty();
    }
}

// Usage
if (ValidatorUtils.isBlank(input)) { ... }
✓ Java 8+
public interface Validator {
    boolean validate(String s);

    static boolean isBlank(String s) {
        return s == null ||
               s.trim().isEmpty();
    }
}

// Usage
if (Validator.isBlank(input)) { ... }
Widzisz problem z tym kodem? Daj nam znać.
📦

Better organization

Keep related utilities with the interface, not in a separate class.

🔍

Discoverability

Factory and helper methods are found where you'd expect them.

🧩

API cohesion

No need for separate *Utils or *Helper classes.

Stare podejście
Utility classes
Nowoczesne podejście
Interface static methods
Od JDK
8
Poziom trudności
Początkujący
Static methods in interfaces
Dostępne

Available since JDK 8 (March 2014)

Before Java 8, utility methods related to an interface had to live in a separate class (e.g., Collections for Collection). Static methods in interfaces let you keep related utilities together. Common in modern APIs like Comparator.comparing(), Stream.of(), and List.of().

Udostępnij 𝕏 🦋 in