Java – good programming style when dealing with multiple objects
I've been programming a software version of a board game So far, I have written classes corresponding to physical objects on the game board I write program logic well, but I find that many logic classes need to access the same object
At first I was passing the appropriate object to the called method, but it became very cumbersome, especially when these methods needed many objects to perform their tasks To solve this problem, I created a class that initializes and stores the objects I need This allows me to call assets Dice () to access objects of any class
But now that I've thought about it, it doesn't seem right That's why I'm here, I'm afraid I created some classes Is this fear groundless, or did I create a recipe for disaster?
Solution
You're basically single To a large extent, this is a bad model By allowing any part of your application to access such global data almost at any time, you will eventually encounter spaghetti that is difficult to maintain, debug and most importantly test code
I think it's best to create a "context" containing the current dice, fragments, etc., and pass the context to the method / class that needs to use it as needed It's clean, yes, but it's painful everywhere However, you can gain the advantage that you can track who is accessing the context, and you can also create a simulation context for testing If the context is passed to a high-level object and must be passed to its child components, the context and where it comes from are known from beginning to end
In addition, ideally, it's good to make the context immutable This may not be possible However, if you can create a new context that captures the current state and is immutable, you can reduce more surprises from the application