Please join us at the new JavaWorld Q&A Forums. Your existing login will work there. The discussions here are now read-only.


JavaWorld Talkback >> 958783

Pages: 1
Anonymous
Unregistered




Encapsulation broken!
      #5362 - 01/19/04 09:54 AM

This article claims to care for better encapsulation. It says that one should not expose the fields via getters and setters. I agree with that: A class should have an interface that is motivated "from the outside": by the way the developer wants the client objects to handle the instances of the class, not by its inner structure.
This means:

- an Account class should have the operations void deposit(Amount) and void withdraw(Amount) instead of setBalance()
- on the other hand, an Amount class may well have the operation Amount getAmount() (which is a getter, is it not?)

The "getter" operations of a class (as viewed from outside) may really be getters (simply returning an instance field), but they may also return computed values. From the outside, nobody knows. That is encapsulation! The interface can stay the same while internal details are changed.

So, there is really no need to use the builder pattern in this context. It is not only unnecessary, but harmful: The pattern itself breaks encapsulation (which is what the article originally declared to preserve). It is because the class has the responsibility to secure the consistency of its instances, the class invariant. Importing and exporting the whole state of an object in one step forces the UI to duplicate all this knowledge about the behaviour and concistency rules (e.g. that if one attribute is changed, another one has to be computed again) and thus breaks encapsulation.


Post Extras: Print Post   Remind Me!   Notify Moderator  
cvogt dot org
Unregistered




Re: Encapsulation broken! [Re: Anonymous]
      #48943 - 06/11/07 03:04 PM

I know, this answer comes quite late and I wonder if anybody will ever read it - but:

You are wrong. The import/export methods of the object are the place to implement the validation and return Exceptions to the Builder in case of error. (Exception safety is important here.) The Builder then can use the Exceptions to display error messages or propagate them to a high UI element.

This approach limits the coupling of the object's data to one between the Builder and the object. It is not coupled with the higher UI, in which the Builder is embedded. Using getters and setters directly in the UI causes it to be coupled to the object's data (members).


Post Extras: Print Post   Remind Me!   Notify Moderator  
Pages: 1



Extra information
0 registered and 1 anonymous users are browsing this forum.

Moderator:   

Print Topic

Forum Permissions
      You cannot start new topics
      You cannot reply to topics
      HTML is disabled
      UBBCode is enabled

Rating:
Topic views: 5511

Rate this topic

Jump to

Contact us JavaWorld

Powered by UBB.threads™ 6.5.5