Copying getters/setters for array/Collection fields

704 views
Skip to first unread message

Pr0methean

unread,
Jan 31, 2018, 8:39:21 AM1/31/18
to Project Lombok
For array and Collection<> fields, I often have to write my own getter and setter just to make a defensive copy. Why not have an option in @Getter and @Setter to do that? For example, this:

@Getter(copy=true)
@Setter(copy=true, includeFinalCollections = true)
public class Example {
 
private String[] strings = new String[10];
 
private final String[] finalStrings = new String[10];
  private final List<Object> objects = new ArrayList<>();
}

might become this:

public class Example {
 
private String[] strings = new String[10];
 
private final String[] finalStrings = new String[10];
  private final List<Object> objects = new ArrayList<>();

 
public String[] getStrings() {
   
return strings.clone();
  }

 
public void setStrings(String[] strings) {
   
if (strings.length == this.strings.length) {
     
System.arraycopy(strings, 0, this.strings, 0, strings.length);
   
} else {
     
this.strings = strings.clone();
   
}
 
}

 
public String[] getFinalStrings() {
   
return finalStrings.clone();
  }

 
public void setFinalStrings(String[] finalStrings) {
   
if (finalStrings.length != this.finalStrings.length) {
     
throw new IllegalArgumentException("New finalStrings must be same length");
   
}
   
System.arraycopy(finalStrings, 0, this.finalStrings, 0, finalStrings.length);
 
}

 
public List<Object> getObjects() {
   
return new ArrayList(objects);
 
}

 
public void setObjects(Collection<? extends Object> objects) {
   
this.objects.clear();
   
this.objects.addAll(objects);
  }
}


Reinier Zwitserloot

unread,
Mar 18, 2018, 10:12:21 AM3/18/18
to Project Lombok
clone() usually doesn't work, so this feature would require adding a complex mechanism for lombok to figure out _HOW_ to make a defensive copy. Also, making defensive copies of large data structures then means that .get() is pragmatically speaking not a near zero impact side effect free method which is  bad.

Two good reasons not to try to fit this into lombok.
Reply all
Reply to author
Forward
0 new messages