Java Practice:返回作为参数传递的相同对象

yad*_*dab 8 java

在下面的代码中,updateWithContex返回作为参数的相同对象是否真的是不好的做法?

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)
    {
       //
    }
}
Run Code Online (Sandbox Code Playgroud)

在C++中,我看到过这样的代码:

 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.
   }
Run Code Online (Sandbox Code Playgroud)

这也错了吗?

Jör*_*ann 10

返回一个对象将建议您的API用户不会更改传入的对象,而是返回一个新的修改对象.为了清楚说明情况并非如此,我建议将返回类型更改为void.

  • 这取决于你如何定义"根本错误"...是否使该方法无法使用?不会.你的名字会被其他任何需要打电话给你方法的人诅咒吗?大概! (2认同)