Re: Rectangle question

David Jordan <[email protected]>
Newsgroups gmane.org.user-groups.trijug.juglist
Message-ID <[email protected]>
One of the main reasons to use encapsulation is to preserve the  
semantic integrity of an instance by ensuring that the values of its  
data attributes are "semantically sound". Often when combining several  
data attributes (or combining two or more of anything in life) to  
represent a certain abstraction and serve a particular purpose, there  
are interdependencies among them that must be preserved. In databases  
the phrase used is "semantic integrity constraints". You also have the  
case where a given attribute needs to be constrained to particular  
values. Encapsulation serves to localize and minimize the scope of  
those functions that can directly modify the data. These functions are  
usually written by the designer/implementer that knows/understands the  
interdependencies and value restrictions and writes code that  
guarantees it. Another reason for encapsulation is information hiding,  
to hide the specific implementation details for the class.

Yet for extremely simple cases like this, it is not that important.  
For a class like Rectangle, except possibly ensuring that width and  
height are positive, no other constraints probably exist.

Some people think they are being good object programmers practicing  
encapsulation by taking a class with 5 data attributes, and they add  
getters and setters for all 5 attributes (which solely perform a  
return or assignment of the attribute, respectively). That is not  
encapsulation. In cases like Rectangle, that is essentially what such  
methods would do.

Yes, public final is read-only, after initialization, which also holds  
for non-public data.

David Jordan

On Sep 18, 2008, at 10:15 PM, Douglas Ivers wrote:

> I noticed recently that Rectangle has public fields...
>
> Rectangle r = new Rectangle();
> r.x = 5;
> r.y = 10;
> int area = r.width * r.height;
>
> Convenient to use, but bad design, right?
> Under what scenarios does it make sense to break encapsulation like
> this in my own classes?  Never?  Single thread only?  Classes with no
> methods?  Only for primitives in which any/all values are acceptable?
>
> If a primitive is declared public final, is this akin to a read-only
> field?
>
> Thanks for any advice,
> -Doug
>
>
> _______________________________________________
> Juglist mailing list
> [email protected]
> http://trijug.org/mailman/listinfo/juglist_trijug.org
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.