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; } }
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
posted
0
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...
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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.