Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of parameter inside method, is this 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 this is an anti pattern, what is it called? The problem (possibly) is that you are implicitly changing parameter and using the changed value.
I just want to know what is this anti-pattern know as

Thanks

like image 397
roundcrisis Avatar asked Dec 28 '12 12:12

roundcrisis


People also ask

Is it bad practice to modify parameters?

It's considered bad practice in general, though some people overlook it as you can see in the other answers. For parameters like primitives that are directly passed in by value, there is no advantage in overriding the original variable.

Can you modify parameters in Java?

You can change that copy inside the method, but this will have no effect on the actual parameter. Unlike many other languages, Java has no mechanism to change the value of an actual parameter.

How do you pass by reference in Java?

Java doesn't support pass-by-reference. Primitive data types and Immutable class objects strictly follow pass-by-value; hence can be safely passed to functions without any risk of modification. For non-primitive data types, Java sends a copy of the reference to the objects created in the heap memory.


1 Answers

It is a side effect.

These are normally not good and considered to be a code smell as it makes it difficult to reason about and understand code.

However, this pattern is sometimes useful.

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

like image 124
Oded Avatar answered Oct 29 '22 21:10

Oded