Prevent classes from changing the state of objects

Asked

Viewed 137 times

1

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

Assuming there is a Pattern to design a java class design that can or even affects the state of the objects.

  • The question has the design Pattern tag. You want to know if you have any Pattern for this?

  • 1

    @Igorventurelli, that’s right! In the case of Design Pattern Observer if I’m not mistaken monitor the status of an object. So the way we design a class affects the behavior of objects.

2 answers

2

You must create immutable classes where the state of the object cannot be changed after its creation.

String is an example of unchanging 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 without methods set.

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

Based in this reply.

1

These are immutable objects where after being created, the object has no way to change its internal state, and this is obtained through deprivation of attribute definition forms such as access methods like setx, another convention is to leave the attributes as final as they will not be amended.

And in the case of Compositions there must be a way to have only 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 return a new created object.. Using the attributes of the current instance, and thus always generating a new object..

So either deprive modification of attributes or can be changed return a new object .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.