Search code examples
javaclassjava-recordjava-16

Multiple records inside the same .java file


We can always have multiple classes inside a .java file. Considering encapsulation and that each class consists of multiple lines of code it always made sense to have 1 class (don't talk about nested classes) inside 1 .java file.

Now that records come into play and they can be as little as 1 line of code. Does it make sense to encapsulate multiple records inside the same .java class?

For example we could have

DTO.java file which would contain

record Employees(List<Employee> employees) { }  //This is just a wrapper class that we normally need in order to return a list of objects in rest web services
record Employee(String name, Integer age, List<Attribute> attributes){ }
record Attribute(String name, String value) { }

If no record has the public access modifier then we are allowed to contain all of them in a file with the name DTO.java

As I view it, it does not seem very good to have 3 .java files with only 1 line of code inside each one.

However we can still face issues like these described here multiple classes inside same java file


Solution

  • Right now there is no official way to do it.
    As a workaround you could create an empty interface and put all your records inside, for example if your controller is CompanyController, I would create an interface called CompanyPort with all dto records inside

    CompanyPort.java:

    public interface CompanyPort {
          record Employees(List<Employee> employees) { } 
          record Employee(String name, Integer age, List<Attribute> attributes){ }
          record Attribute(String name, String value) { }
    }
    

    Hope that would help