Question

Which method is better?:

add(new Label("label", new PropertyModel<String>(cat, "name")));

or

add(new Label("label", cat.getName()));

I tried to find any information about comparison.. but couldn't find anything How I understand the first method is for read/write logic and the second for read only logic, (if I am not right please write me). But for read only logic which better is?

Was it helpful?

Solution

They're functionally different.

The first one says: whenever this component is re-rendered, refresh the value. The second one says: display the value as it was at the time of creation.

Which one do you need? If you want a dynamically refreshing label, you have no choice, it's PropertyModel or CompoundPropertyModel (see later).

If you want it to stay the same, even if the underlying object changes, you can't use PropertyModels.

However, if you are absolutely sure that cat.getName() is never going to change, and therefore the two versions behave the same way, I personally wouldn't use PropertyModel for three reasons:

  1. It breaks encapsulation: in the absence of a getter, it will try to access the private field itself.
  2. As @Jesse pointed it out, it's "magic". If you refactor your class and rename your fields, your PropertyModel will break.
  3. It's not easier to read or maintain. Granted, it's not that much harder either but why add any unnecessary complexity when you're not getting anything out of it? If you put cat.getName() there, you can "click through" in your IDE, your label will show up in a search for all invocations of the getName() method and so on.

If you have many components referring to fields of the same object, you can consider using CompoundPropertyModels, which, although still suffer from problems 1 and 2, make your code look a lot cleaner.

If you have three or fewer components like this though and you don't need a dynamic model, just use the modelless format.

OTHER TIPS

This version is the better of the two options you gave:

add(new Label("label", new PropertyModel(cat, "name")));

It allows the value rendered on the page to update if the page is repainted later after the cat's name has changed.

The second option will only ever display the cat's name as it was at the time that the Label was created. It will never change if the cat's name changes.

There is something to be said for the dangers of using PropertyModel. It is "strings" programming. You compiler is not helping you verify the correctness of the property name "name". If you later refactor your code and change the name of the property to something like "firstName", then you will have to manually find all the places where you reference the old property name and change them by hand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top