标签云

微信群

扫码加入我们

WeChat QR Code


possible duplicate of Why use getters and setters?

2018年09月27日46分55秒

Note that most of the arguments for using accessors still work even if your accessors exposes a collection to the caller. If you're worried about encapsulation, simply clone the collection before passing it to the caller, or before overwriting the old collection value.

2018年09月26日46分55秒

I just wanted to say that I found your last point (whether methods or data drive the structure) particularly insightful. Thanks!

2018年09月27日46分55秒

If you later wanted to enhance your class to take some action when X or Y changes, it is much easier with the getters and setters.

2018年09月27日46分55秒

That's the distinction though - if I store a point I don't expect it to do anything but store information. It's all a matter of what the class is going to be used for.

2018年09月27日46分55秒

... and what the class might be used for in the future. Often worth thinking through possible future changes.

2018年09月26日46分55秒

What if you decide there are minimum and maximum legal values for X and Y? Then you might well want to enforce it in your non-existent getter and setter for X and Y.

2018年09月27日46分55秒

I love properties too. Shame C++ doesn't have them.

2018年09月27日46分55秒

LOL, I feel yah! That's why in C# they introduced the concept of Public Foo Foo { get; set; } so that you don't even have to create a private member variable

2018年09月26日46分55秒

An obvious justification is that setFoo() can do checks on foo if it fits into allowed range, for example. Also (when there is no setFoo), you can have a private member of class "FooImpl extends Foo" and have getFoo() return it as Foo, allowing you to change implementations at will.

2018年09月27日46分55秒

quant_dev yes it can, but in practice it almost never does. I don't think I have ever seen validation done in the bean, it's alwasy done sometime beforehand (e.g. part of the lifecycle of the web framework if we're talking about the web). Domain objects are always more flexible sans logic

2018年09月26日46分55秒

Jon, they could really use properties in Java

2018年09月26日46分55秒

Right... just realized my point is already in StackOverflow ;) stackoverflow.com/questions/24626/… And also: c2.com/cgi/wiki?EncapsulationIsNotInformationHiding

2018年09月26日46分55秒

Sorry for the delay, Ed: I did not check that question until now: you should leave a comment on my answer: it does appear on my response tab of my profile

2018年09月27日46分55秒

Interesting paper, which does not contradict the fact that, as I said, encapsulation can be viewed as a process including 'information hiding' decision.

2018年09月26日46分55秒