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?
@Stateless
,@Stateful
or@Singleton
. But sometimes, interfaces are needed. With EJB, if you would like a remote service, you need an interface annotated with@Remote
. But do not let the exception becomes the rule. When a remote access is needed, create an interface with only the methods you would like to expose and make your bean implement it. – OverissueUserService userService = new DefaultUserService; ... UserService cachedUserService = new CachedUserService;
– Robber