Hi,
I'm currently practicing my java by creating a basic android app using libgdx. Each screen has its own class. I wanted to improve code legibility, so I created additional classes which are called as objects to hold different functions. For example:
public class Screen { ScreenA a; ScreenB b; ScreenC c; public Screen(){ a = new ScreenA(); b = new ScreenB(); c = new ScreenC(); } public void doStuff(){ a.method(); b.method(); c.method(); } }
However, the methods in the additional classes usually depend on objects or methods stored in the other classes. To get this to work I had to add a reference to the other objects in each object's constructor. For example:
public class Screen { ScreenA a; ScreenB b; ScreenC c; public Screen(){ a = new ScreenA(); b = new ScreenB(a); c = new ScreenC(a,b); } public void doStuff(){ a.method(); b.method(); c.method(); } } public class ScreenB { ScreenA a; public ScreenB(ScreenA a) { this.a = a; } }
Although I'm not sure if this is a good way to go about it. e.g. what if ScreenA needs to reference ScreenB? Another way I could do it would be to have the methods reference the other objects themselves. For example:
public class Screen { ScreenA a; ScreenB b; ScreenC c; public Screen(){ a = new ScreenA(); b = new ScreenB(); c = new ScreenC(); } public void doStuff(){ a.method(); b.method(a); c.method(a,b); } }
I'm not sure what is best in terms of best practice. Is there a better way to go about doing this? Also how this would impact performance compared to having all the code within the class. I would love to hear what you guys think.
Thanks in advance!