There are times when I will need to modify a value passed into a method from within the method itself. An example would be sanitizing a string such as this method here:
void SanitizeName(string Name)
{
Name = Name.ToUpper();
//now do something here with name
}
This is purely harmless since the Name
argument is not being passed in by reference. However, if, for some reason, a developer in the future decides to have all values passed in by ref, any sanitizing of the string will affect the value outside the method which could have detrimental results.
Therefore, instead of reassigning to the argument itself, I always create a local copy like so:
void SanitizeName(string Name)
{
var SanitizedName = Name.ToUpper();
//now do something here with name
}
This ensures that changing thow the value is passed in will never affect the goings on outside the method, but I am wondering if I am being excessively paranoid about this.
Name = Name.ToUpper();
makes the code harder to follow in your head as the value ofName
changes. Your second example is not only more future-proof, it's easier to reason what it's doing.if (param == NULL) param = default_value;
?by ref
which was not passed that way beforehand, and so converting local access to a non-local access for some reason, he has always to check the consequences carefully.