Name Service Class Conventions

I am developing a simple Java application to perform CRUD operations with a database through a RESTful API. It is divided into three levels: controller level, service level and DAO level.

I usually create a service interface for each domain object. Let's 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 this interface in the service class:

 public class UserServiceImpl implements UserService { ... } 

This approach, in my opinion, has several drawbacks:

  • This makes me call the specific class something other than UserService , although I only have one specific implementation of this interface
  • All different services do not implement the same interface.
  • There is an explosion of interfaces that all behave the same.

Another approach

I would create an interface that would implement all the services:

 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 functions provided by this interface. Then I have a specific service class that implements this interface with a parameter of type User :

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

Thus, my services have names like UserService , which, in my opinion, are cleaner and more readable.

Questions

  • What is the naming convention of class names? What do you usually do?
  • Should I name a specific UserService class if that sounds like an interface?
  • What about the Impl suffix? Does it convey anything about the implementation?
+5
source share
1 answer

To answer your questions:

  • There is no specific convention for designating classes of service . They are classes, so they must be the only noun (s) in CamelCase : Customer , Company , Employee , UserService , WrapperManager , FileStream , etc.

  • Just because the UserService sounds like an interface to you does not mean that it is one. You should also not call your UserService class if you do not want to. It is up to you at 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 Apple is an apple, not an App . Moreover, Impl nothing about implementation (in other words, business logic).


For more information, check out the following great answers:

+5
source

Source: https://habr.com/ru/post/1205846/


All Articles