Java – Best Practices for Naming Classes and Packages

class-designjavanamingpackage-managers

Apart of the code conventions to use camelCase, PascalCase etc., are there any conventions for naming packages and classes in Java?

For example, I have an mvc project and the main package is com.myproject. In this package I have:

  1. com.myproject.model
  2. com.myproject.view
  3. com.myproject.controller.

Is there any convention or best practise to give a name to the class in these 3 packages? Like for the package 1 avoid model in the classname, or something like this? And if I want to use the same class name like User, what is better: to use UserModel, UserView, UserController, or give the same name to the 3 classes?
Is there some kind of best practise or naming convention to do this?

Best Answer

Short answer: Naming two classes the same in the same project/library/context is not advisable.

Aside from the obvious inconvenience, there is a deeper point why it isn't a good idea and neither is your proposed package naming. We as developers are responsible for modeling business problems, and our naming vocabulary should reflect this fact. This is kind-of the point of Domain Driven Design.

Putting the technology above the actual function might be logical for us, because we are more interested in technology, patterns, architecture and things like that, but makes our model less expressive, less maintainable.

My point is: Package names and class names should reflect business concepts. There should be no model, view, controller packages, there should be no UserModel, UserController classes, etc.

Model the problem, not the technology! Find suitable abstractions straight from the business requirements and hide implementation details, like the fact that you are using MVC.