Java practice: returns the same object passed as a parameter
•
Java
In the following code, isn't it bad that updatewithcontext returns an object with the same parameters?
class SomeClass{
Foo updateWithContex(Foo foo){
foo.setAppId(i);
foo.setXId(index);
//.....
return foo;
}
}
class Foo{
public void setAppId(int appId)
{
//
}
public void setXId(int appId)
{
//
}
public void changeState(X x)
{
//
}
}
In C, I have seen such code:
BigObject&
fastTransform( BigObject& myBO )
{
// When entering fastTransform(),myBO is the same object as the function
// argument provided by the user. -> No copy-constructor is executed.
// Transform myBO in some way
return myBO; // Transformed myBO is returned to the user.
}
Is that wrong?
Solution
Returning an object will advise your API users not to change the incoming object, but to return a new modified object To make it clear that this is not the case, I suggest changing the return type to void
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
