I have the following class:
public class Person
{
public String Name { get; set; }
}
I have a method that takes in Person
and a String
as parameters:
public void ChangeName(Person p, String name)
{
p.Name = name;
}
Since Person
was passed by reference, it should change the Name
of the passed instance.
But is this method more readable than the one above?
public Person ChangeName(Person p, String name)
{
p.Name = name;
return p;
}
Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.
Passing value objects by reference is in general a bad design. There are certain scenarios it's valid for, like array position swapping for high performance sorting operations. There are very few reasons you should need this functionality. In C# the usage of the OUT keyword is generally a shortcoming in and of itself.
The reason is simple: if you passed by value, a copy of the object had to be made and, except for very small objects, this is always more expensive than passing a reference.
What is surprising is that passing a complex object by reference is almost 40% faster than passing by value. Only ints and smaller objects should be passed by value, because it's cheaper to copy them than to take the dereferencing hit within the function.
Is it more readable? No. In fact you may be doing more harm them good.
By having it return a Person object, it might lead you to believe that instead of modifying the Person parameter, it is actually creating a new Person based on p but with a different name and someone could incorrectly assume that p is never changed.
Either way, if you have a method that has no affect on the class it is apart of it should probably be static. That helps you know for sure that it doesn't affect its class. Only have the method return a value if you need it to return a value.
So here is my recommendation for this method:
public static void ChangeName(Person p, String name)
{
p.Name = name;
}
There isn't anything right/wrong with either approach. Depends on what your program needs.
Returning the parameter passed into a method is rarely needed as it is always possible for the user to just use the variable passed as argument instead.
It, however, gives you the flexibility of eventually overriding this implementation, or passing this implementation into another function which accepts delegates with similar signatures. Then you can pass in other implementations that does not return the same Person object.
Do it only if you really need the flexibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With