Package Naming – Should Package Names Be Singular or Plural?

namingobject-orientedpackages

Often, in libraries especially, packages contains classes that are organized around a single concept. Examples: xml, sql, user, config, db. I think we all feel pretty naturally that these packages are correct in the singular.

com.myproject.xml.Element
com.myproject.sql.Connection
com.myproject.user.User
com.myproject.user.UserFactory

However, if I have a package that actually contains a collection of implementations of a single type – such as tasks, rules, handlers, models, etc., which is preferable?

com.myproject.tasks.TakeOutGarbageTask
com.myproject.tasks.DoTheDishesTask
com.myproject.tasks.PaintTheHouseTask

or

com.myproject.task.TakeOutGarbageTask
com.myproject.task.DoTheDishesTask
com.myproject.task.PaintTheHouseTask

Best Answer

Use the plural for packages with homogeneous contents and the singular for packages with heterogeneous contents.

A class is similar to a database relation. A database relation should be named in the singular as its records are considered to be instances of the relation. The function of a relation is to compose a complex record from simple data.

A package, on the other hand, is not a data abstraction. It assists with organization of code and resolution of naming conflicts. If a package is named in the singular, it doesn't mean that each member of the package is an instance of the package; it contains related but heterogeneous concepts. If it is named in the plural (as they often are), I would expect that the package contains homogeneous concepts.

For example, a type should be named TaskCollection instead of TasksCollection, as it is a collection containing instances of a Task. A package named com.myproject.task does not mean that each contained class is an instance of a task. There might be a TaskHandler, a TaskFactory, etc. A package named com.myproject.tasks, however, would contain different types that are all tasks: TakeOutGarbageTask, DoTheDishesTask, etc.