Course contentsShow
← Java
Lesson 2488 of 2,87047. Java Platform Module System (JPMS)Free lesson

Best Practices: Minimizing Exported API Surface

Follow encapsulation principles by exporting only the packages that form your module's public API, keeping internals private.

Best Practices: Minimizing Exported API Surface

What You'll Learn

You'll learn why limiting what you exports from a module is crucial for maintainability, flexibility, and strong encapsulation.

The Core Principle: Export Only What Others Need

When designing a module, think of it like a building with a lobby and private offices. Your exports declarations are the lobby—the official entrance where outsiders can enter. Everything else stays behind locked doors.

The golden rule: Export only the packages that form your module's public API. Keep implementation details, helper classes, and internal utilities private by not exporting them.

Why Minimize Exports?

  1. Flexibility to change: Non-exported packages are invisible to other modules. You can refactor, rename, or delete internal classes without breaking anyone's code.

  2. Clearer API boundaries: When your module exports only 2-3 packages instead of 10, users immediately understand what they should depend on.

  3. Stronger encapsulation: Even public classes in non-exported packages cannot be accessed from outside your module. This enforces true information hiding.

Example Strategy

// module-info.java
module com.example.library {
    exports com.example.library.api;      // Public API - stable
    // NOT exported: com.example.library.internal
    // NOT exported: com.example.library.util
}

Users can only access com.example.library.api. Your internal utilities remain completely hidden, giving you freedom to evolve them.

The Analogy

Think of your module like a smartphone: you expose a touchscreen interface (exported API) but hide all the circuit boards, chips, and wiring (internals). Users don't need access to internal components, and hiding them lets you upgrade hardware without changing the interface.

Key Takeaway: Export the minimum necessary surface—only packages that define your module's contract. Keep everything else private to maximize flexibility and maintainability.