在下面的代码中,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)
{
//
}
}在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.
}这也是错误的吗?
发布于 2012-01-26 16:26:39
返回一个对象会提示API的用户,传入的对象不会改变,而是返回一个新的修改过的对象。为了明确这一点,我建议将返回类型更改为void。
发布于 2012-01-26 16:21:56
您的代码应如下所示:
class SomeClass{
void updateWithContex(Foo foo){
foo.setAppId(i);
foo.setXId(index);
//.....
}
}这是一种糟糕的做法,因为您将引用传递给了foo对象,因此您可以在updateWithContex方法中更改它,而无需将其返回给该方法。再说一次,请记住,在使用Java时,始终要引用Java。可以肯定的是,在其他地方没有办法做到这一点-它将始终是对一个对象的引用。Java没有这样的东西: fastTransform( BigObject& myBO )。
发布于 2012-01-26 16:23:27
我看不出有什么问题,这是API设计的问题。使用您发布的代码,您可以执行以下操作
someClass.updateWithContext(new Foo()).changeState(x);而不是
Foo foo = new Foo();
someClass.updateWithContext(foo);
foo.changeState(x);第一个代码片段是比第二个更好的fluent interface示例。
https://stackoverflow.com/questions/9015357
复制相似问题