Search code examples
oopencapsulationooad

Encapsulation. Well-designed class


Today I read a book and the author wrote that in a well-designed class the only way to access attributes is through one of that class methods. Is it a widely accepted thought? Why is it so important to encapsulate the attributes? What could be the consequences of not doing it? I read somewhere earlier that this improves security or something like that. Any example in PHP or Java would be very helpful.


Solution

  • Is it a widely accepted thought?

    In the object-oriented world, yes.

    Why is it so important to encapsulate the attributes? What could be the consequences of not doing it?

    Objects are intended to be cohesive entities containing data and behavior that other objects can access in a controlled way through a public interface. If an class does not encapsulate its data and behavior, it no longer has control over the data being accessed and cannot fulfill its contracts with other objects implied by the public interface.

    One of the big problems with this is that if a class has to change internally, the public interface shouldn't have to change. That way it doesn't break any code and other classes can continue using it as before.

    Any example in PHP or Java would be very helpful.

    Here's a Java example:

    public class MyClass {
        // Should not be < 0
        public int importantValue;
        ...
        public void setImportantValue(int newValue) {
            if (newValue < 0) {
               throw new IllegalArgumentException("value cannot be < 0");
            }
        }
        ...
    }
    

    The problem here is that because I haven't encapsulated importantValue by making it private rather than public, anyone can come along and circumvent the check I put in the setter to prevent the object from having an invalid state. importantValue should never be less than 0, but the lack of encapsulation makes it impossible to prevent it from being so.