Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, Prevent a field from being changed after being returned by instance method

Tags:

java

In a software development class at my university, the teacher kept mentioning that on a quiz we needed to make sure that a field returned by a getter needed to be "protected." I guess she meant that nothing outside the class should be able to change it. She didn't give much more of an explanation than that.

For instance:

class Foo {
    string[] bar = <some array contents>;

    public string[] getBar() {
        return bar;
    }
}

Any code calling getBar would be able to modify the elements in that array. How do you prevent that from happening? I'm assuming that the object itself should be able to modify the array, just not anything outside the object.

This isn't homework help since the quiz is a couple of weeks old. I simply want to understand Java better since my teacher didn't explain very well.

Update: The teacher wouldn't merely allow us to use protected as the access modifier on the field.

like image 1000
Bob Wintemberg Avatar asked Dec 02 '22 08:12

Bob Wintemberg


1 Answers

You either use a collection and wrap it in Collections.unmodifiable*() or you defensively copy your array, collection or object if its mutable (which arrays always are).

For example:

class Foo {
    private String[] bar = <some array contents>;

    public String[] getBar() {
        return bar == null ? bar : Arrays.copyOf(bar);
    }
}

What you have to watch out for is that this is a shallow copy (so is clone). Not sure what your teacher's problem with clone was.

like image 180
cletus Avatar answered Dec 04 '22 01:12

cletus