From the course: Test-Driven Development in Spring Boot with JUnit and Mockito

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Refactoring the service

Refactoring the service

- [Instructor] Time for my favorite part, refactoring. Let's go and have a look at our task service code, and there are two obvious areas where we can improve. We'll have other methods that find a task by ID and that's eventually going to lead to duplicate code. We could extract this logic in its own methods, though, to be honest if you can do it in a one liner, I don't always say that's necessary. Then we can also focus on making the code more readable. Remember I used T for a variable name? That's a poor practice. Here's our updateTaskStatus. As I said, I'm going to extract a logic for finding a single task. I'm going to make a method, public Task getTaskById and that's going to use an ID. What am I going to do here? Well, I'm going to say return taskRepository.findById, passing in the id. And this is an optional. I said I was going to return a task, so I'm going to say for now, because I did not specify anything else yet, orElse null. Then on this line, instead of doing this, I…

Contents