8 java naming-conventions service-layer
我正在开发一个简单的Java应用程序,用于通过RESTful API对数据库进行CRUD操作.它分为三层:控制器层,服务层和DAO层.
通常,我为每个域对象创建一个服务接口.说,User:
public interface UserService {
List<User> getAll();
User create(User entity);
void update(User entity) throws Exception;
void delete(Long id) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)
然后我在服务类中实现该接口:
public class UserServiceImpl implements UserService { ... }
Run Code Online (Sandbox Code Playgroud)
我认为这种方法有几个缺点:
UserService,尽管我只有该接口的一个具体实现我将创建一个所有服务都将实现的接口:
public interface CrudService<T> {
List<T> getAll();
T create(T entity);
void update(T entity) throws Exception;
void delete(Long id) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)
所以我选择名称CrudService来传达该界面提供的功能.然后,我有一个具体的服务类,用类型参数实现该接口User:
public class UserService implements CrudService<User> { ... }
Run Code Online (Sandbox Code Playgroud)
这样我的服务就有了UserService我认为更干净,更易读的名字.
UserService当听起来像界面时,我应该命名一个具体的类吗?Impl后缀怎么样?它是否表达了有关实施的任何信息?回答你的问题:
命名服务类没有"特殊"约定.他们是类,因此他们应该是一个名词(或多个)在单数形式,首字母大写:Customer,Company,Employee,UserService,WrapperManager,FileStream,等.
仅仅因为UserService听起来像是一个接口,它并不意味着它就是一个.UserService如果您不想,也不必为您的课程命名.最后由你决定.
Impl听起来很丑,看起来很吵.不要使用它.不要使用前缀或其他后缀.用整个词.记住基础:类是对象,所以a Apple是苹果,而不是App.此外,Impl没有传达有关实现的任何信息(也称为业务逻辑).
有关详细信息,请查看以下优秀答案: