I know there are similar questions already, but looking at them I still have some doubts about how I should design my code. I have a service that allows for User
registration / login /update / delete. The thing is that the User
is an abstract type, which contains the data typeOfUser
based on which the actual registration / update / delete methods should be called, and right now I do that in a switch-case
block. I'd like to replace that with some better design.
UserController.java
public class UserController {
public UserDto register(UserDto user) {
switch(user.getTypeOfUser()) {
case DRIVER: return driverService.register(user);
case CUSTOMER: return customerService.register(user);
// ...
}
}
public UserDto update(UserDto user) {
switch(user.getTypeOfUser) {
case DRIVER: return driverService.update((DriverDto) user);
case CUSTOMER: return customerService.update((CustomerDto) user);
// ...
}
}
public UserDto login(long userId) {
loginService.login(userId);
UserBO user = userService.readById(userId);
switch(user.getTypeOfUser) {
case DRIVER: return DriverDto.fromBO((DriverBO) user);
case CUSTOMER: return CustomerDto.fromBO((CustomerBO) user);
// ...
}
}
// ...
}
I understand that something like Visitor
pattern could be used, but would I really need to add the methods of registration / login /update / delete in the Enum
itself? I don't really have a clear idea on how to do that, any help is appreciated.
service.register(user)
once instead of having aswitch
statement. – LuingVisitor
pattern solves a very specific problem and almost always an overkill in most cases (if not all). See my answer for a way to address this with simple Polymorhism.. – Saville