Вопрос

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

Это было полезно?

Решение

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.

Другие советы

I have a different point of view.

Despite the little problems that change parameters value can introduce in debugging process or code readability, it don't make sense to me call this practice as "anti-pattern".

Based on modern OO-languages design like Java or C#, I support the idea that, if it is ugly, wrong or not recommendable to change parameters values, they'd have done defined type parameters as copy of instances, rather than references.

And disagreeing with what Oded said, I think ref or out keyword should be used only in contexts where you really want to change the entire instance value, replacing it completely. To use one of this keywords just to tell "hey guy, the parameters values can change during the execution stack" sounds a little bit careless to me. What if one of your clients see the function signature and really believes that he can replace the entire thing? (in a situation that is not expected behavior).

Assuming the type of parameter isn't really object, but rather is a class type which contains a writable property or field called SomeProperty, then when the method enters, the value of parameter will be the identity of some object (say, the 459,192nd object created since the program began). So far as I can tell, the value of that parameter (meaning the identity of the object to which it refers) will continue to be the same throughout the method.

Changing the value of the passed-in parameter (e.g. saying parameter = someOtherObject) may be a code smell unless the method is sufficiently small that it's obvious what's going on.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top