Isn't it true that a class with public variables is considered weak in Encapsulation and is it not a bad design practice?
If such is the case why does java.awt.Dimension have 2 public variables width and height?
I think that exposing public fields is not a violation of encapsulation itself. Encapsulation is the property of entities, that hide inside themself a complex inner structure. This complex structure can't be accessed directly and therefore not being risked to be broken. It is accessed only through public methods, which make their work well and don't corrupt the complex inner structure. For example, we don't have access to HashMap's hashtable directly and we can't corrupt it. We only use get and put methods, that care of hashtable state properly. But where is the complex structure of Dimension object? What things get broken when we just write d.width = 23?
I think there are reasons to use public getters/setters instead of public fields in this case: taste and conventions. The latter is more significant, I suppose. But it also depends on where and for what we apply this conventions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With