When to use a Composite and when a Component

Team,
I am reviewing Vaadin Flow and I must say you all did a very nice jobs to bring Client and Server programming together and let them work seamlessly together. Love te see how easy it is to use Polymer within Vaadin.

Just getting my head around when to use extend a Component and when a Composite. Both can do the same, not sure?

Gr.
Marc.

Hi Marc!

Glad that you liked our job, that’s awesome.

As for the Composite usage, yes, they are doing the same from the representation point of view: you can construct the same web page with both.
The difference is on a server side: Composite allows you to conceal the actual component implementation (for instance, Icon) and make it look like Component class for other java developers.

Here’s an example:

If you want to create a reusable custom component class
NumberField
for inputting only integer values, you could just simply extend
TextField
, and in the constructor call:

setPattern(“[0-9]
*”);
setPreventInvalidInput(true);

The problem with this is that now the
NumberField
has all the same public methods that
TextField
has. So the user of the component can for example call
setPattern()
again and allow inputting something else than numbers into it. You don’t want
NumberField
to have that method.

To avoid this, you can hide the
TextField
API by wrapping it inside a
Composite
:

public class NumberField extends Composite {
public NumberField() {
getContent().setPattern(“[0-9]
*”);
getContent().setPreventInvalidInput(true);
}
}

Now you can decide what API to expose to the user. The
TextField
has
setValue()
and
getValue()
methods for type String but those aren’t inherited anymore and you could implement those methods for the int-type to make the
NumberField
serve it’s purpose better and do the String-int conversions for the user.

I hope this helps :slight_smile:

Is the setPattern method available only for Vaadin 10?