Game Code Architecture Advice

Godot Version

Godot 4.7

Question

Hello! I have a question that’s more about broad coding practices rather than a specific Godot problem. I hope this is a good place to ask it! If it matters, I use C#, but most of this isn’t really language-specific as far as I can tell.

I’ve been reading a little bit about code architecture, which is a topic I haven’t learned about in any formal context, but I find it interesting, and it seems like it could be very important. A common idea that I’ve come across is that circular dependencies/references are something to be avoided. If class A refers to class B, class B should not also refer to class A. I’m starting a new Godot project, and I want to keep this principle in mind and avoid circular dependencies, but I’m finding it very difficult to wrap my head around. There are already multiple situations where I find myself having to jump through strange hoops to avoid them, and it feels like I’m making things more complicated for little, if any, gain. I understand that circular dependencies can cause memory leaks if one isn’t careful, as well as potential recursive errors, and they are apparently a sign of more deeply flawed design. I’ve also used C++ a little bit in the past, where circular dependencies are just not possible, because script build order determines what can reference what. I worry that I’m just following advice I read online without fully understanding it though, and that’s making things real messy.

Here’s one example. My game has turn-based combat, and has two classes called Actor and Ability. An Actor is a player character, enemy, or other participant in a battle, and an Ability is something an Actor can do on their turn. Abilities can target other Actors in different ways (an attack might only target enemies, while a buff can only target allies). My Actor class needs to hold a collection of Abilities, so that each Actor knows what it can do. The Ability class also needs some sort of GetTargets function, which takes a collection of all the Actors in the battle and returns the ones that are valid targets. But now the two classes have references to each other.
It seems like the simplest solution to this problem is to use interfaces. I make IActor and IAbility interfaces, which Actor and Ability respectively implement. Then Actor can hold a collection of IAbilities that it can use, and Ability.GetTargets can take and return a collection of IActors. Now Ability and Actor don’t directly reference each other. Unfortunately, it ends up being a lot trickier than that. IActor and IAbility cannot both depend on each other, since that would just be another circular dependency. This means either Actor’s collection of Abilities can’t be part of the IActor interface, or Ability.GetTargets can’t be part of the IAbility interface. Either way, if I start with an object of IActor type, there is no way to get to the set of targets of one of that actor’s abilities.
The problem gets worse when other systems need to interact with these classes, such as the UI. My plan is for them to communicate via an event bus, which is a solution I’ve used before and seen suggested many times for game dev, but is prone to circular dependencies. Let’s say I have an EventBus class. Actor and Ability both need to be able to send messages on that bus, so they need references to it. That means EventBus can’t have references to Actor and Ability themselves, so if I want to be able to send a message that includes one of those classes (such as “X actor has chosen to use Y ability”), I need the EventBus to pass those objects as IActor and IAbility objects. But again, either IActor doesn’t know what abilities it can use, or IAbility doesn’t know what targets it has, if not both. I’ve barely started the project, and I’m already in a convoluted mess of a situation where I kind of have two slightly different versions of most of my classes, and only one of those versions can actually do all the things it’s supposed to. And sure, I could cast an IActor to an Actor when I receive it from an event, but that feels like a pretty bad code smell in its own right. The whole point of an interface is that if you’re referring to one, you don’t care what specific implementation of it you’ve been given. If I decide I want to make an ActorV2 class later that also implements IActor, but I’m casting IActor to Actor all over the place, everything’s broken.

Another, more general example of the problem is in my state machine code. I’m more or less using StateMachine and State classes that I’ve used before in other projects. But as-is, StateMachine needs to reference State, so that it knows what state it’s in, and State needs to reference StateMachine, so that it can tell the machine when to transition to a different state. I can wrap both classes in interfaces to do something similar to what I did with Actor and Ability, but I just end up with similar problems again. I suppose State could just have a delegate for StateMachine.ChangeState rather than a reference to StateMachine itself, and that might be a good enough solution in this simple case, but it’s only going to get messier when my state machines start interacting with other systems.

I’m also skeptical that this interface solution actually does anything to prevent memory leaks. I still have object A holding a reference to object B, and B holding a reference to A, it’s just that they know each other by slightly different names. This is a frequently suggested solution to the problem of circular dependencies, so I assume there is some benefit to it, but it’s hard to see what that actually is. If I don’t actually understand the point of what I’m doing, I probably shouldn’t do it until I can figure that out.

Overall, it feels like I’m trying to slap a band-aid on my problem, and it just isn’t working very well. It seems like there are two reasonable solutions: “I’m overthinking all of this and circular dependencies aren’t that big a deal actually,” or “The structure of my code is fundamentally flawed and I need to rework it from the ground up.” I’m really struggling to think of completely different approaches to these problems, though. If my Ability class doesn’t know who it can target, where should that information be? If my Actor class doesn’t know what abilities it can perform, what class does? If I don’t have an Ability class at all, how do I encapsulate all the different choices a character has on their turn? Is the answer really to just ignore what seem to be common best practices, and keep my classes as tightly interconnected as they want to be? Maybe well-architected code really is this complicated, and I just need to get good and figure it out? I know these are big, general questions, but I could really use a nudge in the right direction. Thank you for reading all this, I appreciate it!

Don’t let abilities deal directly with actors. Let actors deal with actors.

On the other hand, having some circular dependencies is not the end of the world.

Btw in C++, classes can cross reference each other.

In my mind, you’re overthinking it. You’re letting a single principle dictate how your code should operate. It’s good to be a critical thinker but too much thinking won’t get you anywhere.

As @normalized said: “[…] having some circular dependencies is not the end of the world.”

With regards to the principle, don’t forget that you are specifically talking about circular referencing – not coupled classes. Classes that depend upon each other is not uncommon. Especially for games where entities frequently interact with one another. That said, tightly coupled systems is another one of those things that is said to be bad practice – but sometimes it can’t be avoided without using convoluted approaches. It’s all a balancing act.

If you feel the need to avoid circular references, just construct a linear line of actions from A->Z. That is, define a clear handling of data from the initial event to the final outcome. I think you’ll find that simply passing the relevant data (either via a data struct or through a set of arguments) to your abilities is all you need to avoid circular references.

Reference example

Actor: Has information
Ability: Processes given information and performs an action

ACTOR (1) > ABILITY > ACTOR (2, 3, 6, 11)
*There is no circular referencing since the ability operates on a data structure, not a class ref.


Maybe it’s not the best explanation, but I hope it makes sense. Let us know if you have any other concerns.

I understand that idea in the abstract, to let actors deal with actors. But I can’t think of a way to do that here in practice. Different abilities need to be able to target different types of actors (an attacking ability might target one enemy, or three adjacent ones, or all of them. A healing ability might target a single ally, or all of them, or even just the user). I don’t see a way to encode that information in the Ability class without it depending on the Actor class, and I don’t know how I could put it in the Actor class in a way that accounts for every type of Ability. I guess I could make a big enum of every possible type of targeting, have Ability just store one of those, and then have Ability convert each value of the enum to a targeting function. That feels messier though. And of course, Abilities actually do things to their targets too, so the effect of an Ability will also need to reference those Actors to do things to them. An enum containing every possible effect of an ability would be really cumbersome, and at that point the Ability class is basically just a collection of enums, and maybe a name and a description. Maybe that is the way to do it, but it feels like my classes are no longer properly encapsulating the behaviour of the objects they represent. Instead of Ability just doing what it’s supposed to do, Actor has to look up what it does and what it does that to, in some massive lookup table that I have to manually update every time I want an Ability to do something new.

Overall though, I am starting to lean in the direction that I’m worrying too much about this, and unless I can boil this all down to a simpler solution that still avoids circular dependencies, I might let some of these classes reference each other directly. That’s also good to know about C++ if I ever use it again. In any case, thank you for your help!

That is kind of good to hear, that I’m probably overthinking it. You’re right that I’m letting this one principle dictate the whole structure of my code, and that’s part of what’s bothering me about it. If I’m having this much trouble avoiding circular dependencies in the structure of my code, then that might mean the structure is fundamentally flawed.

That is interesting, that you say it’s about avoiding specific objects referencing each other, rather than classes being coupled. I guess I might be conflating two different ideas, avoiding circular references between instances and avoiding tight coupling between classes. Some of what I was reading was definitely talking about circular dependencies, saying that if class A knows about class B, class B should never know about class A. Maybe I’m taking it too seriously though, and maybe it’s not practical to follow that perfectly in a project as complicated and interconnected as a data-heavy game like this. Like you said, keeping track of how data is handled should make it relatively easy to avoid circular references, and keeping classes less coupled is something I can keep as a goal, but not such a hard rule. I can try to apply it to larger systems rather than individual classes (so for example, these data classes can depend on each other, but they’re separate from the UI, and don’t depend on any of its classes).

Thanks for your help!

You seem to have succumbed to the dark side of object oriented programming :slight_smile:

One of the big promises of OOP is that it lets you model the real world i.e. model in the actual problem domain. So why don’t you do just that? Follow the semantics of your problem domain and organize accordingly.

In the real world, Abilities don’t do things to Actors. So why insist on that? Instead, Actors use Abilities on other Actors. It’s a very important distinction that can completely change how you think about the problem and organize the solution. Think about it. If you have an ability to punch me on the nose, it’s not the punching ability that’s punching my nose. It’s you using the ability.

So Abilities have no business operating on Actors. They merely let Actors do things to other Actors.

@Sweatix already explained how you can do this in practice here:

If you feel the need to avoid circular references, just construct a linear line of actions from A->Z. That is, define a clear handling of data from the initial event to the final outcome. I think you’ll find that simply passing the relevant data (either via a data struct or through a set of arguments) to your abilities is all you need to avoid circular references.

That said, you probably don’t want to have a broad base class such as Actor. Unless all Actor types are very similar in technical sense, i.e. you can be 100% sure that they’ll all inherit the same node class. Remember that you’re inside a game engine. You’re bound to plug your class hierarchy somewhere into engine’s class hierarchy. Engine’s class hierarchy is technical. It may not be “compatible” with your game’s semantic class hierarchy.

And all that said, you shouldn’t worry about “architecture” at all before you have a working gameplay prototype that to a large degree fleshes out the functionality. Make a dumb but working prototype first. Turn it into a beautiful “architecture” later, when you’re certain what exactly you’re modeling.

I was about to comment that this will be a trigger point for some here, but @normalized has already got there! :rofl:

Tightly coupled is fine, but can cause you to have to refactor lots of code even with a small change.

No coupling or loosely coupled via events is also fine, but creates extra complexilty due to having to create the events in the first place, and can be more difficult to debug.

Abstraction is fine, but can cause you to get into decisions as to where something should live.

Composition is fine, but keeping a track of what snippet of code is doing what can sometimes cause headaches.

I’ve never managed to quite get head around interfaces properly yet, I really should change that.

@normalized will tell you just to stick everything in the one class and be done with it. :sweat_smile:

(btw this is s a friendly dig, not in any way being malicous)

To OOP or not OOP that is the question, reality is that any or all the above is fine, you do you.

Lol. I’m a simpleton. My logic is as follows:
If you don’t separate things that belong together - you won’t find yourself awkwardly coupling them later.
And if you don’t couple them - you won’t have to worry about decoupling.
Easy peasy :smiley:

Don’t you mean a singleton … :wink:

I think maybe you are doing yourself a disservice there.

If you have a situation where a character has an ability list and each ability needs to know which character its associated with you could use a global storage pattern …

class_name character_ability_link

with member dictionary of the form [‘character name’, ability]:

var dict:Dictionary[ String, ability ]= {}

Then you can perform bi directional lookup operations without causing a circular dependency.

Honestly… get a room.

The topic is solved.

Where is “there”?

Obviously, I wasn’t completely serious as I was responding to a joke - with a joke.

Seriously though - Don’t separate everything that can be separated just to produce as small pieces as possible. Some things naturally belong together. And some things need to be bigger than your gurus might pretend to like. Don’t fragment your organization beyond necessary, simply because some ideology claims it’s better to do so.

“Architecture” topics are never “solved” :rofl: