I have a business requirement that requires checking on a person's first name to ensure it does not have the character "1". The model:
public class Person
{
public string FirstName { get; set; }
}
I started writing the following function to perform the check:
public Person CleanPersonFirstName(Person person)
{
var clean = person;
if (clean.FirstName.Contains("1"))
{
clean.FirstName.Replace("1", "");
}
return clean;
}
But I am not sure if it is justifiable creating a new copy of the Person object, perform the check, and return the copy.
Would the following be a better approach?
public void CleanPersonFirstName(ref Person person)
{
if (person.FirstName.Contains("1"))
{
person.FirstName.Replace("1", "");
}
}
[Edit] - Thank you all for all comments posted. I would consider this thread to have gathered sufficient feedback to get me thinking.
[Edit2] - Stumbled across this article on pure function (context is JS, but the message is still applicable): https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976
Key messages:
// impure addToCart mutates existing cart
const addToCart = (cart, item, quantity) => {
cart.items.push({ // Here the input gets mutated.
item,
quantity
});
return cart;
};
As mentioned by the article: The problem with this is that we’ve just mutated some shared state.
Revised version:
// Pure addToCart() returns a new cart
// It does not mutate the original.
const addToCart = (cart, item, quantity) => {
const newCart = lodash.cloneDeep(cart);
newCart.items.push({
item,
quantity
});
return newCart;
};
var clean = person;
is merely a reference assignment, no clone or copy has been made: both clean and person refer to the same exact instance. So, between your two options, they are not different: both modify the one and onlyPerson
object involved. FYI, when you get that far, I favor returning a new object rather than modifying the one in place.