Related Blog

Null value in the service

by Zhao Liqiang
Java Engineer

December 9, 2019

There is a UserSearchService that provides user queries:

public interface UserSearchService{

List<User> listUser();

User get(Integer id);

}

The problem

There is a UserSearchService that provides user queries:

Problem site:

For object-oriented languages, the level of abstraction is of particular importance. Especially for the abstraction of the interface, it accounts for a great proportion in the design and development, and we want to program the interface as much as possible in the development.

For the interface method described above, it may be inferred that it contains the following two meanings:.

ListUser (): query user list

Get (Integer id): queries a single user in all the development, the TDD pattern advocated by XP can guide us to define the interface very well, so we use TDD as the “promoter” of the development code.

For the above interface, when we use TDD for the test case first, we find the potential problem:

ListUser () if there is no data, does it return an empty collection or null?

If get (Integer id) does not have this object, does it throw an exception or return null?

Go deep into listUser

listUser()

This interface, I often see the following:

public List<User> listUser(){

List<User> userList = userListRepostity.selectByExample(new UserExample());

if(CollectionUtils.isEmpty(userList)){//spring util

return null;

}

return userList;

}

This code return is null, from development experience, for collection such return value, it is best not to return null, because if returned null, will cause a lot of trouble for callers. You will leave the risk of this call to the caller to control. If the caller is a cautious person, he will make a conditional judgment as to whether it is null. If he is not cautious, or if he is an interface-oriented fanatic (of course, interface-oriented programming is in the right direction), he will call the interface according to his own understanding, without judging whether it is null or not. If so, it is very dangerous, it is likely to have null pointer anomalies! Judging by Murphyundefineds law, “problems that are likely to arise will certainly occur in the future!” Based on this, we optimize it:

public List<User> listUser(){

List<User> userList = userListRepostity.selectByExample(new UserExample());

if(CollectionUtils.isEmpty(userList)){

return Lists.newArrayList();//guava

}

return userList;

}