0

今天我在我们的 GWT 代码中看到了一个方法,如下所示:

public Map< String, ResponseObject > getResponse( RequestObject requestObject ) {
    remoteServiceAsync = GWT.create( RemoteServce.class );
    final Map< String, ResponseObject > responseReference = new HashMap< String, ResponseObject >();

    remoteServiceAsync.doServerCall( requestObject, new AsyncCallback< ResponseObject >() {
      public void onFailure(Throwable caught) {
         // TODO: Do something with errors.
      }

      public void onSuccess( ResponseObject response ) {
        responseReference.put( "value", response );
      }
    } );

    return( responseReference );
};

我认为,这是一个非常糟糕的做法。你觉得这段代码怎么样?它适用于所有浏览器吗?它是一个“ valid”选项来阅读data吗?不得不提的是,数据是在程序后期访问的,所以不缺数据。

4

2 回答 2

0

返回那个真的很糟糕。Hashmap它完全打破了RPC advantages

在那个方法中,它立即返回一个empty hash-map并稍后插入一个Map没有用的值。

并初始化

甚至不检查(remoteServiceAsync!=null)以下行

remoteServiceAsync = GWT.create( RemoteServce.class );

因此它将为每次调用进行初始化。

于 2013-02-25T11:38:48.010 回答
0

这里有2点要强调——

1)我们不知道异步调用什么时候返回,所以我们可以使用return语句来返回从RPC返回的对象。因此,responseReference 将始终为空。

2)我们不需要在每次需要触发异步调用时创建 RPC 实例。所以单例模式推荐用于这种类型的场景。

您的代码片段可以重构如下 -

ServiceAsync serviceasync = null;

getServiceAsync()
{
     if(serviceAsync == null)
     {
         serviceAsync = GWT.create( RemoteServce.class );
     }
     return serviceAsync;
}

AsynCallBack asyncCallBack;

getAsyncCallBack()
{
      if(asynvCallback != null)
      {
           return asyncCallback;
      }
      return new AsyncCallback< ResponseObject >() 
            {
                  public void onFailure(Throwable caught) 
                  {
                       // TODO: Do something with errors.
                  }

                   public void onSuccess( ResponseObject response ) 
                   {
                        // Do processing here with the response object ...
                   }
            } );    
}

现在在调用 getResponse() 方法的地方替换该方法调用,执行以下操作 -

getServiceAsync().doServerCall( requestObject, getAsyncCallBack() );

因此,将只有一个服务实例和一个 asyncCallBack 实例。避免了创建多个对象,从而提高了性能。

于 2013-02-25T14:54:53.073 回答