Reference Value Parameter VS Return value, which is good?

If we want to change a value in one object, we can use two different methods, we just want to know which one is better or not a big difference between them.

  • 1.
void SomeMethod() { UserInfo newUser = New UserInfo(); ModifyUserInfo(newUser); //Modify UserInfo after calling void method GetUserInfo } void ModifyUserInfo(UseerInfo userInfo) { userInfo.UserName = "User Name"; ..... } 
  1. 2.
 void SomeMethod() { UserInfo newUser = New UserInfo(); //Assign new userinfo explicitly newUser = GetUserInfo(newUser); } UserInfo ModifyUserInfo(UseerInfo userInfo) { userInfo.UserName = "User Name"; ..... return userInfo; } 
+4
source share
6 answers

I would prefer a third:

  void SomeMethod() { UserInfo newUser = GetUserInfo(); } UserInfo GetUserInfo() { UserInfo userInfo = New UserInfo(); userInfo.UserName = "User Name"; ..... return userInfo; } 

This basically allows GetUserInfo handle all the details of the UserInfo build, and your calling code should not worry about any details other than the returned object.

+5
source

From the second signature - UserInfo ModifyUserInfo(UseerInfo userInfo) -, I can assume that it will process UserInfo as if it were unchanged.

Perhaps I am mistaken in thinking that he will make a copy of the transferred object and return a new, modified one.

+3
source

The first method is fine. This is not a link parameter following the link: ref UserInfo userInfo, and it is not recommended. One of the rules of FxCop: Do not pass types by reference, but this is not what you do.

0
source

Answer to the answer: None of them are good. It:

 UserInfo newUser = New UserInfo(); newUser.Modify(); 

or, if UserInfo is better modeled as a Value Object :

 UserInfo newUser = New UserInfo(); var u = newUser.Modify(); 

although in the latter case, I would call the method something else.

0
source

You may even have

 UserInfo ui = new UserInfo {UserName = "User Name", ...} 

(in C # 3.0). But in the general case, if it is a reference type, do not create it every time if it is really not necessary (for example, for System.String). I am talking about the second example.

0
source

First method. The second makes no sense; without studying the code (or documentation), there is no way to know that it returns the same instance of UserInfo that was passed.

0
source

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


All Articles