Defensive Copy: Should I List in Javadoc?

As far as I understand, getters / seters should always make copies to protect data.

However, for many of my classes, it is safe for the recipient to return a reference to the requested property, so the following code

b = a.getB();
b.setC(someValue);

actually changes the state of object a. If I can prove that this is normal for my class, is it good practice to implement getter this way? Should the user be notified of this, for example, in Javadoc? I think this will violate the paradigm hiding the implementation, so I should always assume that state a has not changed and call setter

b = a.getB();
b.setC(someValue);
a.setB(b);

Thanks in advance S

+3
source share
4 answers

: A B, A B, , . , ( A , B), - , , .

, , , .

get(), :

, (, , Javadoc). , .

+4

, setC , , . ( "" - , .)

, IMHO. . , .

, , .

TMI ( ) JavaDoc.

+4

, , , . , , , .

, API, , , ; , "" !

// Immutable interface definition.
public interface Record {
  String getContent();
}

// Mutable implementation of Record interface.
public class MutableRecord implements Record {
  private final String content;

  public MutableRecord(String content) {
    this.content = content;
  }

  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }
}

// API that only exposes the object via its Record interface.
public class MyApi {
  private final MutableRecord mutableRecord;

  public Record getRecord() {
    return mutableRecord;
  }
}
+3

You will get the wrong copy before you know it! And then you have a real mistake, not a potential one.

Therefore, if you trust the client code, do not worry about it .

This is very academic, and I personally have never had a problem with this. I will also disable the check immediately in FindBugs (Java), for example ...

And if there is a problem, whoever reads JavaDoc and the like? Is anyone there?

-2
source

Source: https://habr.com/ru/post/1717494/


All Articles