标签云

微信群

扫码加入我们

WeChat QR Code


possible duplicate of Why use getters and setters?

2019年02月23日13分09秒

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.

2019年02月22日13分09秒

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

2019年02月23日13分09秒

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.

2019年02月23日13分09秒

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.

2019年02月23日13分09秒

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

2019年02月22日13分09秒

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.

2019年02月23日13分09秒

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

2019年02月23日13分09秒

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

2019年02月22日13分09秒

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.

2019年02月23日13分09秒

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

2019年02月23日13分09秒

Jon, they could really use properties in Java

2019年02月22日13分09秒

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

2019年02月22日13分09秒

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

2019年02月23日13分09秒

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

2019年02月22日13分09秒