Conventions for naming service classes

user1019830 picture user1019830 · Oct 30, 2014 · Viewed 14.9k times · Source

I'm developing a simple Java application for doing CRUD operations against a database through a RESTful API. It's divided into three layers: the controller layer, the service layer and the DAO layer.

Normally, I create a service interface for each domain object. Say, User:

public interface UserService {
  List<User> getAll();
  User create(User entity);
  void update(User entity) throws Exception;
  void delete(Long id) throws Exception;
}

Then I implement that interface in a service class:

public class UserServiceImpl implements UserService { ... }

This approach I think has several drawbacks:

  • It forces me to name the concrete class something other than UserService, although I only have one concrete implementation of that interface
  • All the different services do not implement the same interface
  • There's an explosion of interfaces that all behave the same way

Another approach

I'd create an interface that all services would implement:

public interface CrudService<T> {
  List<T> getAll();
  T create(T entity);
  void update(T entity) throws Exception;
  void delete(Long id) throws Exception;
}

So I choose the name CrudService to convey the functionality provided by that interface. Then, I have a concrete service class implementing that interface with a type parameter User:

public class UserService implements CrudService<User> { ... }

This way my services have names like UserService which I think is more clean and readable.

Questions

  • What's the convention for naming service classes? What do you usually do?
  • Should I name a concrete class UserService when that sounds like an interface?
  • What about the Impl suffix? Does it convey anything about the implementation?

Answer

Mihail-Florin Popa picture Mihail-Florin Popa · Jan 7, 2015

To answer your questions:

  • There is no "special" convention for naming service classes. They are classes so they should be a noun(s) in singular form in CamelCase: Customer, Company, Employee, UserService, WrapperManager, FileStream, etc.

  • Just because UserService sounds like an interface to you it does not mean it is one. You also do not have to name your class UserService if you do not want to. It is up to you in the end.

  • Impl sounds ugly and looks noisy. Do not use it. Do not use prefixes or other suffixes either. Use whole words. Remember the basics: classes are objects, so an Apple is an apple, not an App. Moreover, Impl does not convey anything about the implementation (aka business logic.)


For more info, check out the following great answers: