Extending components Best Practice

Dear All,

I’m quite new in Vaadin « World » and I would like to have your point of view regarding this topic

Normal way to add a extend component in a page.

TextField tf = new TextField();
ResetButtonForTextField.extend(tf);
addComponent(tf)

What I do is more like this

ResetButtonForTextField ext = new ResetButtonForTextField(“Caption”)
addComponent(ext.getComponent())

See attachment

Thanks in advance for sharing your expertise.

21031.java (2.01 KB)

Your solution is sort of reversing the roles of a component and extension, and I don’t see anything good in that. It looks like a potential anti-pattern to me, altough it’s difficult to exactly point out why. You might want to add more than one extension to the component, or rather extend the component by inheritance and add extensions to that.

If you want to encapsulate the “resetable” behaviour, why not encapsulate it in the component, by having “ResetableTextField” that extends TextField by inheritance, and adds the extension internally. Then, you could have method to add the ResetButtonClickListener in the component.

ResetableTextField tf = new ResetableTextField("Caption"); tf.addResetButtonClickListener(click -> tf.setValue("")); // Or whatever addComponent(tf); The ResetButtonClickListener could still be internally handled in the extension, but that would be a private implementation matter in the ResetableTextField. (Are there really more than the obvious way to “reset” something?)

Thanks Marko

Well, extending the TextField by inheritance could also have some issues, and you’d maybe want to keep the behaviour separate from the class. Unless there’s some special need to encapsulate the behavour, you could go with using the extension as you use BrowserWindowOpener, not have the extend() as a static method but a normal method in the extension:

TextField tf = new TextField(); ResetButtonForTextField resetButton = new ResetButtonForTextField(); resetButton.addClickListener(click -> tf.setValue("")); // Or whatever resetButton.extend(tf); addComponent(tf) In any case, either this way or my other solution above would seem “good practices” to me.

Note that using an “extend()” method is also a purely arbitrary choice. You might want to give the TextField instance to extend in the constructor for the extension, or in some other way.