aspose file tools*
The moose likes Beginning Java and the fly likes bad encapsulation why? need help! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "bad encapsulation why? need help!" Watch "bad encapsulation why? need help!" New topic
Author

bad encapsulation why? need help!

Joanne Fire
Ranch Hand

Joined: Nov 22, 2001
Posts: 33
Can anyone tell me why the attribute is badly encapsulated? The only thing I see is that there is a missing constructor, but apparently, it's more than that.
Thanks.
Here is the code:
class objectContainingDate
{
private Date myDate;
public void setDate(Date theDate)
{
myDate = the Date;
}
public Date getDate()
{
return myDate;
}
}
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

the date class is mutable so there is nothing stopping a user from getting the date object and changing it without the class knowing...

Dave
Joanne Fire
Ranch Hand

Joined: Nov 22, 2001
Posts: 33
Thanks David!
Originally posted by David O'Meara:
[B]the date class is mutable so there is nothing stopping a user from getting the date object and changing it without the class knowing...

Dave[/B]

David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

There are a number of solutions to your problem...
You can use composition to create a version of Date that is immutable (hides state changing methods) like this:

The problem withtis is that it is NOT a java.util.Date or java.sql.Date
Alternatively you can make your class return DEFENSIVE COPIES of the date. ie it returns a new instance with the same value.

The third way (off the top of my head) is to merge your original class and the Date composition from my first example. ie it will have the usual calls, and the Date calls as well, which get mapped to the inner instance.
Dave.
(ps: everything I know I leant from Effective Java by Joshau Bloch, see the Javaranch Bunkhouse )
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: bad encapsulation why? need help!