Search code examples
javabeansprinciplesinformation-hiding

How does the design of JavaBeans square with information hiding?


Two semesters ago, I had a professor who said:

Some of you have been told to always include setter and getter methods for all private instance variables. I say that this breaks information hiding, and often results in systems where invariants cannot be enforced.

Now, that sounds right to me. But isn't including those kinds of setters/getters a core part of creating JavaBeans? If so, why? If not, what am I misunderstanding about JavaBeans?


Solution

  • Getters and setters are not required in a Java Bean class. All that's required is that the class must be public, it must have a public no argument constructor and it must implement Serializable. However, in order for variables to be discovered automatically when your bean is used you must provide getters and setters following a standard naming convention (getVarname, setVarname...).

    In any case, you want to make externally visible only the variables that have a business being seen outside your class.