Let's say I have a class Comment and I have a private field named commentDate which is a java.util.Date and with a getter named getCommentDate.
Why it's better to return a copy of that date ( return new Date(commentDate.getTime()) ) than simply returning that date...
How can a user change the object state of that Date since it's a getter, not a setter?
Returning references to internal mutable members of a class can compromise an application's security, both by breaking encapsulation and by providing the opportunity to corrupt the internal state of the class (whether accidentally or maliciously).
The mutable class examples are StringBuffer, Java. util. Date, StringBuilder, etc. Whereas the immutable objects are legacy classes, wrapper classes, String class, etc.
I think using mutable objects stems from imperative thinking: you compute a result by changing the content of mutable variables step by step (computation by side effect). If you think functionally, you want to have immutable state and represent subsequent states of a system by applying functions and creating new values from old ones.
Immutable objects are quicker to access and are expensive to change because it involves the creation of a copy. Whereas mutable objects are easy to change. Use of mutable objects is recommended when there is a need to change the size or content of the object.
A major point not yet mentioned is that having the state of an object be mutable makes it possible to have the identityof the object which encapsulates that state be immutable. Many programs are designed to model real-world things which are inherently mutable.
Use of mutable objects is recommended when there is a need to change the size or content of the object. Exception : However, there is an exception in immutability as well. We know that tuple in python is immutable. But the tuple consists of a sequence of names with unchangeable bindings to objects. The tuple consists of a string and a list.
Since java.util.Date
implements Cloneable
you can easily clone the date, as:
public class DateTest {
private Date date;
public DateTest() {
}
public Date getDate() {
return (Date) date.clone();
}
public void setDate(Date date) {
this.date = (Date) date.clone();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With