refactor validate method in HabitAssignServiceImpl
@@ -54,7 +54,10 @@ public class HabitAssignServiceImpl implements HabitAssignService {
@Override
public HabitAssignManagementDto assignDefaultHabitForUser(Long habitId, UserVO userVO) {
User user = modelMapper.map(userVO, User.class);
- Habit habit = validateHabitForAssign(habitId, user);
+
+ Habit habit = habitRepo.findById(habitId)
+ .orElseThrow(() -> new NotFoundException(ErrorMessage.HABIT_NOT_FOUND_BY_ID + habitId));
+ validateHabitForAssign(habitId, user);
HabitAssign habitAssign = buildHabitAssign(habit, user);
enhanceAssignWithDefaultProperties(habitAssign);
@@ -80,7 +83,10 @@ public class HabitAssignServiceImpl implements HabitAssignService {
public HabitAssignManagementDto assignCustomHabitForUser(Long habitId, UserVO userVO,
HabitAssignPropertiesDto habitAssignPropertiesDto) {
User user = modelMapper.map(userVO, User.class);
- Habit habit = validateHabitForAssign(habitId, user);
+
+ Habit habit = habitRepo.findById(habitId)
+ .orElseThrow(() -> new NotFoundException(ErrorMessage.HABIT_NOT_FOUND_BY_ID + habitId));
+ validateHabitForAssign(habitId, user);
HabitAssign habitAssign = buildHabitAssign(habit, user);
enhanceAssignWithCustomProperties(habitAssign, habitAssignPropertiesDto);
@@ -125,15 +131,11 @@ public class HabitAssignServiceImpl implements HabitAssignService {
*
* @param habitId {@link Habit} id.
* @param user {@link User} instance.
- * @return {@link Habit} instance.
*/
- private Habit validateHabitForAssign(Long habitId, User user) {
- Habit habit = habitRepo.findById(habitId)
- .orElseThrow(() -> new NotFoundException(ErrorMessage.HABIT_NOT_FOUND_BY_ID + habitId));
-
- if (habitAssignRepo.findByHabitIdAndUserIdAndSuspendedFalse(habit.getId(), user.getId()).isPresent()) {
+ private void validateHabitForAssign(Long habitId, User user) {
+ if (habitAssignRepo.findByHabitIdAndUserIdAndSuspendedFalse(habitId, user.getId()).isPresent()) {
throw new UserAlreadyHasHabitAssignedException(
- ErrorMessage.USER_ALREADY_HAS_ASSIGNED_HABIT + habit.getId());
+ ErrorMessage.USER_ALREADY_HAS_ASSIGNED_HABIT + habitId);
}
if (habitAssignRepo.countHabitAssignsByUserIdAndSuspendedFalseAndAcquiredFalse(
user.getId()) >= AppConstant.MAX_NUMBER_OF_HABIT_ASSIGNS_FOR_USER) {
@@ -142,11 +144,10 @@ public class HabitAssignServiceImpl implements HabitAssignService {
+ AppConstant.MAX_NUMBER_OF_HABIT_ASSIGNS_FOR_USER);
}
if (habitAssignRepo.findByHabitIdAndUserIdAndCreateDate(
- habit.getId(), user.getId(), ZonedDateTime.now()).isPresent()) {
+ habitId, user.getId(), ZonedDateTime.now()).isPresent()) {
throw new UserAlreadyHasHabitAssignedException(
- ErrorMessage.USER_SUSPENDED_ASSIGNED_HABIT_FOR_CURRENT_DAY_ALREADY + habit.getId());
+ ErrorMessage.USER_SUSPENDED_ASSIGNED_HABIT_FOR_CURRENT_DAY_ALREADY + habitId);
}
- return habit;
}
/**
