Prevent classes from modifying the state of objects

1

How to prevent classes from modifying the state of objects in a class, both Within equal and separate packages?

Assuming there is a pattern for designing a java class design that may or may not affect the state of objects.

    
asked by anonymous 30.03.2017 / 23:41

2 answers

2

You should create immutable classes, where the state of the object can not be changed after it has been created.

String is an example of immutable class, among many others.

public final class Person {

     private final String name;
     private final int age;
     private final Collection<String> friends;

     public Person(String name, int age, Collection<String> friends) {
         this.name = name;
         this.age = age;
         this.friends = new ArrayList(friends);
     }

     public String getName() { 
         return this.name;
     }

     public int getAge() {
         return this.age;
     }

     public Collection<String> getFriends() {
         return Collections.unmodifiableCollection(this.friends);
     }
}

Attributes private and final and no methods set .

An important point added in this example is the use of immutable collections.

Based on this answer.

    
30.03.2017 / 23:56
1

This is immutable objects where after the created object has no way to change its internal state, and this is achieved through deprivation of attribute definition forms such as accessor methods such as setX, another convention is to leave the attributes as final since they will not be changed.

And in the case of Compositions, there should be a way to only have read access to these instances for this class and only the external class can access them.

Another practice is that if there are methods that modify attributes these will return a new created object .. Using the attributes of the current instance, and thus always generating a new object ..

Then either deprive modification of the attributes or if they can be changed return a new object.

    
31.03.2017 / 00:08