Quantcast
Channel: Using java streams to handle incoming API requests - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 3

Answer by TorbenPutkonen for Using java streams to handle incoming API requests

$
0
0

It is true that when you buy yourself a fine hammer, you want to go hitting all kinds of things. And when you buy an angle grinder, the world seems to be full of things that need to be cut apart. Same is with streams, when you learn about them, it seems like every problem must be solved with streams.

But this is not right. Streams are a tool for solving a very specific set of problems and your problem is not one of them.

First of all, whoever reads the code, immediately thinks that there are a multitude of values being processed. Because that is the set of problems streams are used for.

Then they notice the save operation and realize that there's going to be trouble if one of the saves fail.

Then they see the findFirst and start to scream in their heads about terminal operations and how that stream is never going to work correctly.

At some point they go back and realize that it's just a stream of one object and they wasted all this energy for nothing. Because of the stream the code became confusing and less readable.

There is nothing wrong with just laying out method calls next to each other. They're still 100% valid and good stuff. It's really efficient, because there's no unnecessary method calls needing variables stuffed into the stack and no throwaway objects being created.

final Employee employee = employeeMapper.mapToEmployee(request);final Employee savedEmployee employeeRepository.save(employee);final EmployeeDto employeeDto employeeMapper.mapToDto(savedEmployee);

Sure you could nest the method calls, but that's going to be a pain in the ass when one of the method calls throw an exception and you have to start debugging it.

On a related matter, I recommend splitting the employeeMapper to two classes. One that maps the request to Employee and another that maps an Employee to EmployeeDTO. This follows single responsibility principle and helps you keep your classes small and manageable.


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images