开发者

When using Java classes from Jython, do you bother to use the getters and setters? Should you?

开发者 https://www.devze.com 2023-04-10 09:38 出处:网络
It\'s well known that Python classes cannot have truly private members. The not-as-obvious implication of this is that Java classes\' privates are made public to Jython. (Hide thy nakedness, Java!)

It's well known that Python classes cannot have truly private members. The not-as-obvious implication of this is that Java classes' privates are made public to Jython. (Hide thy nakedness, Java!)

So, when using Jython, and accessing a Java classes' privates that would usually be exposed to other Java classes through getters and setters, do you bother to use those methods? Or do you just access the privates directly?

The more pertinent question would be, should you use the getters and setters? If there are side-effects of the methods, then the answer would undoubtedly be 'yes', but if the methods are just there be开发者_如何学Pythoncause someone thought that a putting getters and setters everywhere is The Right Thing to do (IMO it's not, just make the damn thing public), then is there any reason to bother with all of Java's extra ceremony?


Although Jython can make non-public Java members accessible from everywhere, this is a feature that must be enabled explicitly. This alone is reason enough for me to honor the visibility of Java classes, otherwise you are risking works on my machine problems.

More principially, you should use the provided property accessors for classes that are not under your control unless you have a very good reason not to: You never know if future versions of the class will do more than just the bare minimum in their getters/setters.

Jython has the nice feature of hiding the accessor methods of JavaBean properties. Jython converts x.foo += 5 into x.setFoo(x.getFoo() + 5. Because usually the backing field of a property has the same name as the property itself, you may have confused this feature with "Jython makes the backing field accessible" even if it does not. I would definitively use this property-accessed-like-fields syntax of Jython: it makes your code more concise and easier to read.

0

精彩评论

暂无评论...
验证码 换一张
取 消