tags:

views:

38

answers:

2

Hello,

in a définition of a widget, what is a better practice, and why, use the widget himself or the type "higher", example, it's a better practice to do

1) Button myButton; or 2) Hastext myButton; (and set a button later)

thanks for your answer.

+1  A: 

It is usually a good idea to use "higher" types or interfaces. By doing this properly you can hide implementation details. The code that uses an object looks at it as the one of a higher type and it is not important what is actually hiding behind it. This is good because you can easily change an implementation of the object without breaking anything.

For example when defining a panel in an application you should use Panel class instead of its implementation e.g. HorizontalPanel or VerticalPanel.:

Panel myPanel; 

Then you can create a proper implementation of it, e.g HorizontalPanel:

myPanel = new HorizontalPanel();

If you then later decide to change myPanel to be VerticalPanel you will not have to change anything in the code that uses myPanel. Everything will work just fine.

However you must remember that you will be only able to use methods available in Panel class. Additional methods defined in e.g. HorizontalPanel will not be accessible. And this is actually what you should remember when choosing the type of your widgets. Your widgets should be of types which provide methods which you want to use.

In your example using HasText instead of Button isn't probably a good idea because HasText has only methods for setting and getting a text and you probably also want to have access to addClickHandler method available in Button and a few more.

So to summarize it is good to use "higher types" but they should not be "too high" to be useful.

Piotr
Thanks for your very clear explain ! :o)
Yannick Eurin
A: 

The answer to that lies in the Model-View-Presenter pattern, that was introduced in last years Google IO presentation by Ray Ryan. There's also an official tutorial/docs - part 1 and part 2. There are also a number of questions here on SO that cover that topic :)

And a quick answer to your question (that will make more sense once you get familiar with MVP): use interfaces in the Presenter and their implementations in the View :) That way your Presenter stays oblivious to the underlying implementation/Widget you actually used (was it a Button? Or a Label? It doesn't matter, they both implement HasText).

Igor Klimer
Heh, Piotr beat me to it :)
Igor Klimer