Example. Encapsulation danger when returning internal arrays

[comp1110-46]

Suppose we extend the GuestList interface with a method coming() that returns the current list of guests. This seems straightforward, but a naive implementation illustrates a common encapsulation hazard: returning a direct reference to the internal array.

// DANGEROUS — exposes internal state public String[] coming() { return this.data; }

A caller who receives this reference can write list.coming()[0] = "Intruder" and corrupt the guest list without going through add or remove, potentially breaking the data invariant. The correct fix is to return a defensive copy:

// SAFE — caller gets their own array public String[] coming() { String[] copy = new String[this.count]; int i = 0; while (i < this.count) { copy[i] = this.data[i]; i = i + 1; } return copy; }
bars magnifying-glass caret-down plus minus arrow-right xmark