• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bad encapsulation why? need help!

 
Joanne Fire
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 )
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic