7

This is more of a conceptual question.

I had to work on a functionality that had to create a dynamic h:dataTable. And whenever I created a component, I did something similar to this:

DataTable table = (DataTable) FacesContext.getCurrentInstance().getApplication()
                      .createComponent(DataTable.COMPONENT_TYPE);

Using the FacesContext to create everything for me.

However I could just as simply have done this:

DataTable table = new DataTable();

The reason I did it in the first way is that all the tutorials and material I read while developing did it that way, but I never got a clear answer why.

Is there an actual reason why the first is better than the second?

Rodrigo Sasaki
  • 7,048
  • 4
  • 34
  • 49

1 Answers1

8

The Application#createComponent() adds an extra abstract layer allowing runtime polymorphism and pluggability. The concrete implementation is configurable by <component> entry in faces-config.xml which could in turn be provided via a JAR. This allows changing implementation without rewriting/recompiling the code.

It's exactly like as how JDBC API works: you don't do new SomeDriver(), but you do Class.forName(someDriverClassName) which allows the driver to not be a compiletime dependency and thus your JDBC code to be portable across many DB vendors without rewriting/recompiling.

However, if the application is for "internal usage" only and not intented to be distributable (and thus all the code is always full under you control), then runtime polymorphism has not a so big advantage and may add (very minor) overhead.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    Oh, I see now. It actually makes perfect sense, I just never thought of it from that angle. The link you added as reference was also a very big mind opener. Thanks again, @BalusC! I actually thought that it'd be you who would answer this. Good thing I was right :-) Cheers! – Rodrigo Sasaki May 17 '13 at 14:13
  • 1
    I always thought that if you used 'new SomeComponent()' things like adding ajax behaviours would not work... Never to old to learn – Kukeltje Jan 08 '18 at 19:30