Issue
I'd prefer it as a record as there is less boilerplate, but would there be issues?
IntelliJ is suggesting that I turn a basic Java class @Service like this:
@Service
public class LocationService {
private final PlaceRepository placeRepository;
@Autowired
public LocationService(PlaceRepository placeRepository) {
this.placeRepository = placeRepository;
}
public List<PlaceDto> findPlacesByRegionId(Long regionId){
return placeRepository.findByRegionId(regionId).stream().map(place -> new PlaceDto(place.getId(), place.getName())).toList();
}
}
into a Java record @Service like this:
@Service
public record LocationService(PlaceRepository placeRepository) {
public List<PlaceDto> findPlacesByRegionId(Long regionId) {
return placeRepository.findByRegionId(regionId).stream().map(place -> new PlaceDto(place.getId(), place.getName())).toList();
}
}
Solution
You could do that, but records have getters (well without get
prefix). Which Service Layer shouldn't have. Your Service Facade exposes public methods which also are usually @Transactional
, you don't want to mix them with methods that no one is going to use.
Also, records define equals()
& hashCode()
which aren't needed for Service classes either.
In the end the only common theme between Records and Services is that all fields are usually final
and all of them are usually passed via constructor. This isn't much of commonality. So it sounds like a bad idea to use records for this.
Answered By - Stanislav Bashkyrtsev