Change the parameter value inside the method, is it an anti-pattern?

So something like this

public void MyMethod(object parameter) //.... BuildSomething(parameter); BuildLayers(parameter); BuildOtherStuff(parameter); } public void BuildSomething(object parameter) { //... parameter.SomeProperty = "sadsd"; //... } 

If it is an anti-pattern, what is it called? The problem (maybe) is that you are implicitly changing the parameter and using the changed value.
I just want to know that this anti-pattern knows how

thanks

+8
c # anti-patterns
source share
3 answers

This is a side effect .

They are usually not good and are considered code smells, as this makes it difficult to parse and understand the code.

However, this pattern is sometimes useful.

C # codified the ref and out keywords to show that the method is expected to have side effects.

+16
source share

I have a different point of view.

Despite the small problems associated with changing the value of parameters that may arise during debugging or reading code, it makes no sense for me to call this practice an “anti-pattern”.

Based on modern projects of OO languages ​​such as Java or C #, I support the idea that if it is ugly, incorrect, or it is not recommended to change the parameter values, they would make certain parameters of the type as copies of the instances, and not the links.

And disagreeing with what Oded said, I think the ref or out keyword should only be used in contexts where you really want to change the value of the entire instance, completely replacing it. To use one of these keywords, just to say “hey guy, parameter values ​​can change during stack execution” sounds a little careless to me. What if one of your customers sees the signature of the function and really believes that it can replace the whole thing? (in a situation that is not expected).

0
source share

Assuming that the parameter type is not really an object , but rather the type of a class that contains a record property or field called SomeProperty , then when the method comes in, the parameter value will be the identity of some object (say, the 459,192th object created since launch programs). As far as I can tell, the value of this parameter (which means the identifier of the object to which it refers) will remain the same throughout the method.

Changing the value of the passed parameter (for example, the expression parameter = someOtherObject ) can be a code smell if the method is not small enough, which is obvious what is happening.

0
source share

All Articles