Issue
@Service
public class FooService {
public boolean doFoo(List fooList) {
//Code calling List without checking for null, possible NPE
Integer id = fooList.get(0).getId();
//more code
}
}
@Service
public BarController {
@Autowired
FooService foo;
public bar(Optional<Compound> optCompound) {
if (optCompound.isPresent()) {
List barList = optCompound.setList(new ArrayList<>());
//sending List Over to FooService
Boolean isFooDone = foo.doFoo(barList);
}
}
Should I check the list for null value in the service code here?
Integer id = fooList.get(0).getId();
Just on basis of presumption that service call is placed in the controller where the List is already initialized with empty ArrayList?
List barList = compound.setList(new ArrayList<>());
Or should Service code be written independent of the controller?
Solution
The Service code should be written Independent of the controller making the whole architecture as Loosely coupled. So in the future, if you want to change any business logic, it can be changed independently of the controller.
Also, the controller should only redirect the requests based on the requirement for further processing to multiple layers.
In the above code, you can check for an empty ArrayList in the Service layer allowing the controller to only redirect to the service layer.
Any statement related to business logic should be the part of the Service layer and not Controller.
You can use this blog for further reference on Service layer in Spring.
Answered By - Himanshu Jain
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)