Re: Rectangle question
"Richard O. Hammer" <[email protected]>
| Newsgroups | gmane.org.user-groups.trijug.juglist |
|---|---|
| Message-ID | <[email protected]> |
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? I have not yet been converted to the belief that getters and setters are normally a good idea. In fact I think they are often a bad idea. And I think that information hiding is a value which can be carried into places where it does more harm than good. But this question may have to do with where the code is destined to be used. I am writing code which will be used mostly by myself or by others in a small group of which I am a member. Probably this code will not be released to a large set of users as an API. In most of my code I routinely access the fields in other classes directly, without getters and setters. Getters and setters would make my classes longer than necessary and probably slow down the execution. Sometimes I make a field private, but only if I fear its use might be misunderstood. I have tried to understand why Sun and others make such dogged use of getters and setters. The explanation I find is that they know they are making an API which they hope will become a broadly-used standard. They want to be careful about what they promise in the public interface, promising no more than they promise. That leaves them free to change everything else about the interior behavior in a future release, without threatening to break any of their users' code, if such changes become advantageous. Rich Hammer Hillsborough