I have been having fun learning java for years, did a little bit of OOP tutorials and this is the first time I attempt to make a real project. The project is very similar to some top down view tabletop management game with very little graphics. Oddly every thousand line of code I hit my head on a wall and wonder if I need to restructure everything. For example I restructured once to try and adopt some concept of MVC, which I had no knowledge of when I started. I am glad I did.
The wall now : I started reading how we should use global and singleton sparingly when I suddenly could not save my game since I had created a new instance that had static fields (using GSON to save my Game object).
My project structure
- App : gameloop, has Engine class, calls Engine.updateUI() and engine.updateGame()
- Engine is the main controller that has access to all other controllers, creates the game object and updateUI() and updateGame() methods
- Game : contains every object that represent the state of the game so that I can save and load it
- MyData class is a global class that just loads a bunch of text files and provides data for the game but does not need to be saved
So lately I created a class called Finances that had static fields such as cash, waterBill, electricityBill… I can only ever need one instance of Finances in my game so I thought it would be neat to be able to do something like
if Fiances.getCash() == enough doSomething from anywhere in my code, from any controller, to enable and disable buttons for example.
I have another similar class called Updater that has static booleans as flags to schedule an update on certain part of the UI instead of having every UI elements update and query the model 60 fps.
- Add some code to save and load the values of those static fields;
- change the fields to non-static and give Game another parameter called finances that will only be created once.
I was going with the second approach for a while but I realized I was just passing Engine engine everywhere to have access to everything like
I feel like this is just like a global variable but more complicated. Here I am not hoping to code the best code with the best structure and all best practices. I am just looking to improve and learn in a fun way. Most articles I found just end “anyway if you end up with needing many singletons or globals your code probably smells”. That did not help me find a solution.