When should a method of a class return the same instance after modifying itself?
Posted
by
modiX
on Programmers
See other posts from Programmers
or by modiX
Published on 2014-08-19T13:23:42Z
Indexed on
2014/08/19
16:29 UTC
Read the original article
Hit count: 390
I have a class that has three methods A()
, B()
and C()
. Those methods modify the own instance.
While the methods have to return an instance when the instance is a separate copy (just as Clone()
), I got a free choice to return void
or the same instance (return this;
) when modifying the same instance in the method and not returning any other value.
When deciding for returning the same modified instance, I can do neat method chains like obj.A().B().C();
.
Would this be the only reason for doing so?
Is it even okay to modify the own instance and return it, too? Or should it only return a copy and leave the original object as before? Because when returning the same modified instance the user would maybe admit the returned value is a copy, otherwise it would not be returned? If it's okay, what's the best way to clarify such things on the method?
© Programmers or respective owner