Désavantage du pattern JavaBean
Bonjour
je suis en train de lire le livre effective java et en particulier le chapitre sur les constructeurs.
Pour rappeler le contexte, les auteurs y évoquent les avantages d'utiliser les méthodes de fabrique static afin de fournir une instance d'objet et de ne pas fournir de constructeur public.
Ils évoquent les désavantages de JavaBean pattern dont voici l'extrait
Citation:
Unfortunately, the JavaBeans pattern has serious disadvantages of its own.
Because construction is split across multiple calls, a JavaBean may be in an
inconsistent state partway through its construction. The class does not have
the option of enforcing consistency merely by checking the validity of the constructor
parameters. Attempting to use an object when it’s in an inconsistent state
may cause failures that are far removed from the code containing the bug, hence
difficult to debug. A related disadvantage is that the JavaBeans pattern precludes
the possibility of making a class immutable (Item 15), and requires
added effort on the part of the programmer to ensure thread safety.
It is possible to reduce these disadvantages by manually “freezing” the object
when its construction is complete and not allowing it to be used until frozen, but
this variant is unwieldy and rarely used in practice. Moreover, it can cause errors
at runtime, as the compiler cannot ensure that the programmer calls the freeze
method on an object before using it.
Ce que je ne comprends pas c'est la partie suivante:
Citation:
Attempting to use an object when it’s in an inconsistent state
may cause failures that are far removed from the code containing the bug, hence
difficult to debug. A related disadvantage is that the JavaBeans pattern precludes
the possibility of making a class immutable (Item 15), and requires
added effort on the part of the programmer to ensure thread safety.
Est-ce que quelqu'un à déjà rencontré un exemple de cas où un objet peut être dans un état inconsistant et comment peut on rendre la classe immutable dans ce cas ?
Un tel cas me paraît surprenant et je ne vois pas comment on peut y arriver .
Merci