In the following code, is it really bad practice for updateWithContex
to return the same object it took as a parameter?
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 code like this:
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 this also wrong?
In Java, we can pass a reference to an object (also called a "handle")as a parameter. We can then change something inside the object; we just can't change what object the handle refers to.
Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.
Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. This effectively means that objects act as if they are passed to methods by use of call-by-reference.
"In order to return an object from a Java method, you must first declare a variable to hold a reference to the object." So in this case, Ball is a variable that is a reference to the object. Correct? redBall is a reference to the object created by the new Ball("red") statement.
Returning an object will suggest to users of your API that the passed in object will not be changed and a new modified object returned instead. To make it clear that this is not the case I would suggest changing the return type to void
.
Your code should look like this:
class SomeClass{
void updateWithContex(Foo foo){
foo.setAppId(i);
foo.setXId(index);
//.....
}
}
It is bad practice, because you pass the reference to the foo object, so you can change it in updateWithContex method without returning it back the method. Once more, remember that you work always with reference with Java. And fore sure, there is no way how to do it elsewhere - it is going to be always a reference to an object. Java has nothing like this: fastTransform( BigObject& myBO ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With