Video in progress

Strong Middle 🧱 OOP and SOLID

How do package-private and JPMS modules give you encapsulation at a bigger level than `private`?

private only closes a class's insides. Package-private hides a package's internal classes from the outside, and JPMS closes packages that aren't exportsed from other modules, even against reflection: public no longer means "open to everyone".

📖 Answer

In many projects every class is public, because the IDE creates them that way. As a result the whole application ends up using payment.internal.SignatureUtil and you can no longer change it.

Closing things at the package level:

package uz.shop.payment;

public interface PaymentService { ... }        // the only door open to the outside

class DefaultPaymentService implements PaymentService { ... } // package-private
class ClickSignature { ... }                   // package-private
record ClickResponse(...) { }                  // package-private

Spring doesn't get in the way: it scans and injects package-private @Component classes too. Tests in the same package see everything as well.

The limit: in Java, nested packages (payment.click) are not "children": they can't see each other's package-private classes. That's why inside a big module you still end up needing public.

This is where JPMS helps:

module uz.shop.payment {
    exports uz.shop.payment;          // only the API package
    // uz.shop.payment.click, .internal are not exported
    requires java.net.http;
}

Now even a public class in uz.shop.payment.internal is invisible to other modules, and setAccessible(true) doesn't work either (unless it's opensed).

In practice JPMS is rarely used in Spring Boot applications: Spring and Hibernate need opens for reflection, and the setup is heavy. Many teams choose ArchUnit rules or Spring Modulith instead: a test like "other modules may only touch the ..api.. package" fails in CI.