Question

I have a question regarding the Object hierarchical call.

I have four classes namely A, B, C, D.

D will be set in C; C will be in B; B will be in A.

If I want to do something in class D, I have to call a.b.c.d.setWidth("50%");(a, b, c, d are instance of Class A, B, C, d).

Is that fine to call like that? Will that compromise the performance?

Was it helpful?

Solution

The effect on performance will be very slight... the bigger issue is what that does to your object-oriented model.

Having direct access to the members of a class is frowned apon, and you are running risks of NullPointerExceptions.

What you should be more worried about is the readability and maintainability of your code.

OTHER TIPS

It is perfectly legal to call like that. I dnt think it will have performance issues. But the design is not good. You should use getters and setters inside the code. For example : In your case : a.getB().getC().getD().setWidth("50%").

In class A , declare variable of B as private and similarly with class B and C. It will ensure data hiding and encapsulation principles of an Object Oriented design.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top