Design – Is it bad practice to reuse method parameters

designprogramming practices

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.

Best Answer

I think it depends on your coding conventions in your project.

I personally let eclipse automatically add the final keyword to every variable and parameter. This way you see at the first glance if a parameter is reused.

In the project at my job we do not recommend to reuse parameters, but if you just want to call e.g. .trim() or set a default in a null case, we reuse the parameter most of the times, because introducing a new variable is in such cases less readable than the reuse of the parameter.

You should really not reuse a parameter to store a very different content because the name would no longer refer to its content. But this is true for every reassigment of a variable and not restricted to parameters.

So get together with your team and formulate coding conventions which cover this matter.

Related Topic