Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Every top-level public(ish [1]) type declaration requires its own file. It may be irritating but it also brings some clear advantages for compilation speed. You can be irritated by many small files or by longer compilation times.

When you compile a file, the compiler quickly finds all other file dependencies and compiles (or just parses) only them, i.e. given a single file, the compiler knows exactly where to find all the declarations of all the types used in it. This property may not matter for languages that don't have good separate compilation anyway -- and few languages do, which is why people coming from other languages may find the restriction weird -- but Java's separate compilation is excellent. That turns out to also greatly help in-memory compilation for an upcoming feature where we can choose to compile files lazily, on demand: https://openjdk.org/jeps/8304400

To see that that is, indeed, the reason for the restriction, notice that it is only required for public(ish) top-level types. Non top-level public types can also be easily located, and non-public top-level types that are stored in files that don't match their names can only be referenced by code in that file (more precisely, the compiler is allowed to emit an error if they're referenced elsewhere). See the bottom of ยง7.6 of the JLS: https://docs.oracle.com/javase/specs/jls/se20/html/jls-7.htm....

Anyway, the point is that the restriction is there for a good reason. We sometimes entertain removing that restriction (and maybe someday we will), but the compilation benefits have so far turned up to be quite useful. We like our efficient separate compilation -- I don't think any other mainstream language does it as well as Java -- and may be able to get even more out of it.

[1]: Really, any top-level class that is referenced by name from other files.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: