Hello,
I’m currently puzzling over something that came up when i was trying to port some old Delphi source code to vaadin. Here’s the code to a hypothetical View class. The View will have 3 ‘parts’: a header, a footer, and a body.
public abstract class MyView extends VerticalLayout implements View () {
public MyView() {
//wiring code goes here
}
public ComponentContainer createHeader() {
return new DefaultHeader();
}
public ComponentContainer createFooter() {
return new DefaultFooter();
}
public abstract ComponentContainer createBody(); //to be defined in descendant classes
}
If you need a new view, you just have to inherit from MyView, and a proper IDE will generate the abstract method that you have to implement, e.g:
public class HomeView extends MyView {
public ComponentContainer createBody() {
//add contents here
}
}
Now here’s the problematic part, the wiring code in MyView constructor:
//MyView constructor
public MyView() {
ComponentContainer ccHeader = createHeader();
ComponentContainer ccBody = createBody();
ComponentContainer ccFooter = createFooter();
//
if (ccHeader != null) this.addComponent(ccHeader);
if (ccBody != null) this.addComponent(ccBody);
if (ccFooter != null) this.addComponent(ccFooter);
}
The code sort of works, and i kinda like the structure, but Java and the IDE will complain about "
overridable call in method constructor"
at line 3/4/5 above. I understand the problems underlying the java warnings and why it’s not advised, so i suppose my question now is, how do we do this “properly” in java?
Alternative 1: Do not use the constructor for the wiring code, use an init() method instead.
- Pros: retain all the flexibility
- Cons: need to remember calling init() after creating the object (might sound trivial, but i failed this a couple of times with interesting results :D, in general i would normally avoid extra-but-mandatory steps like this)
Alternative 2: Use something like a Factory Method pattern.
- Pros: not sure
- Cons: gets a bit complicated, messier code involving at least 2 new classes
Any opinions/pointers are welcome. Maybe share your favorite way to structure vaadin views/UI if you can?
Thanks in advance,
ts.