Is this a legit use of getter
Lady lady = new Lady();
lady.getWater() = "hot water";
if we suppose getter returns
Class Lady {
public String getWater() {
this.water;
}}
?
Is this a legit use of getter
Lady lady = new Lady();
lady.getWater() = "hot water";
if we suppose getter returns
Class Lady {
public String getWater() {
this.water;
}}
?
Short answer: NO
Long answer: You are misusing the Getter. You have Setters
& Getters
to encapsulate data, i.e. prevent direct access to the member variables. In your Setter
, you might e.g. check that you actually set some kind of water (hot/cold/soapy). If you abuse the Getter to Set data you circumvent that. Also, it runs contrary to the expected use of Getters
, so anyone else working on your code will be in for unpleasant surprises.
To conclude: This is all kinds of bad (I'm not sure it would even work in Java) don't do it!
setFoo(bleh)
and bleh = getFoo()
instead of bar.foo = bleh
and bleh = bar.foo
then there is litte gain. But still,at the very least, you can look at who calls setFoo()
without needing to look at getFoo()
if you want to know writing accesses (or vice versa). BTW: Saying "This is how you get encapsulation"
seems to convey a "this is the truth and the only truth and all who do not agree are idiots" feeling. Not a fan.
– CharonX
May 18 '18 at 09:37
setFoo
isolated from the consumers of getFoo
, because any of them may be relying on any other of them doing a particular thing
– Caleth
May 18 '18 at 09:50
getFoo()
instead of bar.foo doesn't remove knowledge of the user from the underlying code. I really wish getFoo()
could do more than return Foo
- e.g. calculate foo on the fly, or using a cache, or delegating the call to another function. No, sadly getFoo()
HAS to directly { return foo; }
, there is NO way to make that function do anything else, and thus there is NO way to remove the knowledge of implementation details from the user. (/sarcasm)
– CharonX
May 18 '18 at 10:00
Foo getFoo() { return foo; }
is the only way to write a getter. I'm saying having any Foo getFoo()
is unencapsulated, especially if there is also a void setFoo(Foo)
. Why does the world have to know there is a Foo
at all?
– Caleth
May 18 '18 at 12:18
Circle
class with a Point centerPoint
, which has a Point getCenterPoint()
and a void setCenterPoint(Point point)
function. At the very basic that get/set function would only return/assign the centerPoint. If your Circle gets more complex, you could e.g. change the get
function to maybe calculate the centerPoint on the fly (as you now use a 3-point definition of a circle instead of center + radius, for whatever reason). By writing a getter
/ setter
for centerPoint you are able to change the underlying implementation later
– CharonX
May 18 '18 at 13:41