Java – How to Handle Classes with Same Name in Different Packages

coding-standardscoding-styleconventionsjavanaming

Me and my R&D team maintain a large codebase. We've divided our business logic into multiple packages. some of which have classes with identical names.

As you can guess, the names conflict when both classes are referenced in the same Java file.


For example:

com.myapp.model (package)
 - Device (class)
 - ...

com.myapp.data (package)
 - Device (class)
 - ...

We had a debate on what's the best practice to treat these cases and the following options came up:

1st Option

  • Renaming the class, adding a prefix

    ModelDevice
    DataDevice
    

2nd Option

  • Using the full package+class name when both are referenced

    com.myapp.model.Device
    com.myapp.data.Device
    

What's more correct in terms of code management and scalability?

we are currently mixing both approaches and starting to have inconsistency

Best Answer

Use the package name. This type of problem is precisely why Java uses the package naming convention that it does. It prevents these sorts of problems, whether it's two teams in the same company or two teams on opposite sides of the earth.