Coding practice. What coding approach should I use?

Sorry for such an uncertain title. I did not think about the good.

Situation:

  • Have a list of user objects.
  • You must create an array for the UserInfo object.
  • The UserInfo object is created based on the information in the User object. (There is currently a method for this)

What is better in this situation?

  • Should I pass a complete list of User to User to UserInfo methods.
  • or I need to iterate over the list of users and pass the conversion method to each user object and get UserInfo for it.

Examples:

List<User> users = .....; UserInfo[] userInfos = getUserInfoFromUser(users); //(conversion method will loop and generate array, then return it.) 

or

 List<User> users = .....; UserInfo[] userInfos = new UserInfo[users.size()] for (int j = 0; j < users.size(); j++) { userInfos[j] = getUserInfoFromUser(users.get(j)); } 

In the first approach, we pass a large object (a list of users) as an argument, and in the second we call the same method several times. What's better?

The size of the user list will vary from 25-200 objects.

+4
source share
6 answers

What about two conversion methods: one that accepts User and returns UserInfo (this can and probably should be the constructor of UserInfo ), and one that accepts the list executes the loop and internally calls the first?

The size of the list does not matter.

+5
source

I think it depends on how often you do it, because you don’t want to repeat the same loop in several places in your code.

I would suggest creating two methods: one that returns information for one user, and the other that returns information for a list of users:

 public UserInfo[] getInfoForUsers(List<User> users) { UserInfo[] userInfos = new UserInfo[users.size()]; for (int j = 0; j < users.size(); j++) { userInfos[j] = getInfoForUser(users.get(j)); } return userInfos; } public UserInfo getInfoForUser(User u) { } 
+2
source

I prefer the first approach, because it is simple, also the argument will be the address of the users object. In this case, it doesn’t matter, big or small.

0
source

In both cases, Java passes a reference to the object. In the first case, it refers to the collection of users, and in the second, to the user.

0
source

I would recommend using the first option: pass the entire array!

Reducing the number of function calls is definitely paying off.

0
source

There is no difference: in the first version, the implementation of the function will do the second version. In addition, probably, I would like to have a function User β†’ UserInfo.

0
source

Source: https://habr.com/ru/post/1387169/


All Articles