In GWT, why shouldn't a method return an interface?

后端 未结 2 629
梦如初夏
梦如初夏 2021-02-07 06:21

In this video from Google IO 2009, the presenter very quickly says that signatures of methods should return concrete types instead of interfaces.

From what I heard in th

相关标签:
2条回答
  • 2021-02-07 06:43

    This and other performance tips were presented at Google IO 2011 - High-performance GWT.

    At about the 7 min point the speak addresses 'RPC Type Explosion': #4 Watch out for RPC type explosion

    For some reason I thought the GWT compiler would optimize it away again but it appears I was mistaken.

    0 讨论(0)
  • 2021-02-07 06:58

    This has to do with the gwt-compiler, as you say correctly. EDIT: However, as Daniel noted in a comment below, this does not apply to the gwt-compiler in general but only when using GWT-RPC.

    If you declare List instead of ArrayList as the return type, the gwt-compiler will include the complete List-hierarchy (i.e. all types implementing List) in your compiled code. If you use ArrayList, the compiler will only need to include the ArrayList hierarchy (i.e. all types implementing ArrayList -- which usually is just ArrayList itself). Using an interface instead of a concrete class you will pay a penalty in terms of compile time and in the size of your generated code (and thus the amount of code each user has to download when running your app).

    You were also asking for the reason: If you use the interface (instead of a concrete class) the compiler does not know at compile time which implementations of these interfaces are going to be used. Thus, it includes all possible implementations.

    Regarding your last question: all methods CAN be declared to return interface (that is what you ment, right?). However, the above penalty applies.

    And by the way: As I understand it, this problem is not restricted to methods. It applies to all type declarations: variables, parameters. Whenever you use an interface to declare something, the compiler will include the complete hierarchy of sub-interfaces and implementing classes. (So obviously if you declare your own interface with only one or two implementing classes then you are not incurring a big penalty. That is how I use interfaces in GWT.)

    In short: use concrete classes whenever possible.

    (Small suggestion: it would help if you gave the time stamp when you refer to a video.)

    0 讨论(0)
提交回复
热议问题