How to properly organize interfaces and implementations in Java modular project?

323 Views Asked by At

I am looking for a way to properly organize interfaces and implementations in Java 11 modular project.

Considering the simplest case: there is an interface and its multiple implementations. The intention is to expose only this interface and its factory methods as the module API.

MyInterface.java

public interface MyInterface {

  String action(String input);

  //--- factory methods

  static MyInterface createSimple(Object argument){
     return new MySimpleImpl(argument);
  }    

  static MyInterface createComplex(Object a, Object b){
     return new MyComplexImpl(a,b);
  }
}

MySimpleImpl.java

class MySimpleImpl implements MyInterface { ... }

MyComplexImpl.java

class MyComplexImpl implements MyInterface { ... }

Suppose the root package is org.company.myproject.

So module-info.java contains only one export: exports org.company.myproject;


I see several ways to organize the code, for instance the obvious are:

Version 1: Put implementations into a nested package and make them public.

Version 2: Put implementations into the root package and keep them package-private.

At the moment I cannot prefer any of the versions, because the first forces me to break visibility contracts inside the module itself, and the second pollutes the root package making its intentions vague.

Please, help me to understand how to precisely express my intentions for the module's classes visibility inside and outside the module both. Probably, there are best practices for this situation.

0

There are 0 best solutions below