Search code examples
encapsulation

Why encapsulation is good for interchangeability and working in team?


That's my question. Thank you!


Solution

  • Encapsulation is good because you can protect the values of variables and what variables can be seen/edited.

    Here's an example in Java:

    public class Foo {
        private int size;
        private String name;
    
        public int getSize() {
            return size;
        }
    
        public void setSize(int size) {
            if (size > 0)
                this.size = size;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            if (name == null || name.isEmpty())
                return;
            this.name = name;
        }
    }
    

    This makes sure that the variable size is greater than 0 and the value of name isn't empty or null. You can also put checks in the constructor.

    One more thing. If you had made the variable size public, and everyone used fooObject.size=232, and then suddenly you wanted to make restrictions, it would break everybody's code. It's better just to start by using encapsulation.

    Hope this helps :)