Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

java - Is it bad practice to call public object vars and methods from other objects?

Learning Java while working on an image-processing project, I've noticed a bad habbit spring up: I will create an object which will create a different object, passing on some variables and said object in turn creates another object, passing on variables to create it. Often these objects are settings windows that require some user input.

In the end I find myself sometimes referring to parent-object methods/variables using TopObject.SecondObject.methodDoesThing(TopObject.SecondObject.variable,TopObject.variable);

all from within a third object even! Is this as terrible a practice as it feels? How do I avoid it? Should I be copy-pasting any methods I need to reuse? Should I pass on any variables needed in object 3 to object 2, even it 2 wont use it just to avoid calling back to public variables? Or is this fine and am I just overthinking things?

question from:https://stackoverflow.com/questions/65864848/is-it-bad-practice-to-call-public-object-vars-and-methods-from-other-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Having public member variables is bad practice almost always. If they are public it means that they can easily be changed by anyone.

In OOP there is a term called Encapsulation which, really short, means that the code should restrict access to its inner working and structure.

How to avoid such long calls as the ones you described? This is a rather tricky question because it varies from scenario to scenario. My first suggestion would be to read about design patterns. Even though just applying them won't solve the problems, it will give you new ideas on how to properly design your inner code and the structure so that there are well-defined responsibilities.

I would start with a few simple but widely used ones: Factory, Observer, Singleton, Visitor and Model-view-controller. One important thing to keep in mind is that design patterns are guidelines and they can/should be adapted and combined. Applications will use multiple patterns in different parts and for different functionalities.

I am sorry that I can't just give a more direct answer, but for such a question I think it is better to give guidance to the needed reading materials than code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...