Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the good way of returning a mutable object

Tags:

java

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?

like image 873
spauny Avatar asked Jun 28 '11 07:06

spauny


People also ask

Do not return references to private mutable class members?

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).

Which is are the examples of mutable objects?

The mutable class examples are StringBuffer, Java. util. Date, StringBuilder, etc. Whereas the immutable objects are legacy classes, wrapper classes, String class, etc.

Why do we need mutable objects?

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.

What is the difference between immutable and mutable objects?

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.

What is the point of mutability?

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.

When to use mutable objects in Python?

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.


1 Answers

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();
    }       
}
like image 80
Tapas Bose Avatar answered Oct 12 '22 14:10

Tapas Bose