A discussion about loose coupling and loosely coupled code

Godot Version

4.2 (but probably not that important)

Question

I wanted to start a discussion about approaches the community takes to make sure their code is loosely coupled.

This is a topic I’ve been studying for a couple of days, and I think it would be great to have a centralized thread on the topic.

As an example, many tutorials make use of @onready variables and specific paths to exact nodes. These conventions are relatively brittle, as one change to the code can break these references.

One suggestion I’ve seen is to create custom nodes (classes and inheritance). But if one does not know exactly how to handle this, it is common to create tightly coupled OOP code.

What are some methods that in fact make your code loosely coupled? What is the correct way to make use of signals to avoid tight coupling with them?

What is the right way to make use of modules or autoloads? I can see autoloads inadvertently leading to tight coupling, as they are ultimately holding global variables.

It seems to me many of the conventions in our community lead to tight coupling, and even many of the modular tools built into godot can easily be inadvertently tightly coupled.

1 Like

onready is great for static scenes, and allows you to have a single line change if the path changes, (it is more efficient then using get_node, and $ within functions). If you remove the node its a different story, but that is not the fault of the keyword.

Every time you create a script you are inheriting a class, and it isn’t the main cause for the code to become coupled.

Signals; SOLID principles.

Check out Godot’s own documentation on this.

It is true that it could, but it is sometimes necessary. The alternatives are usually far worse to complexity.

The main use of auto loads/singleton is to represent a singular thing that only needs one instance, and can be globally accessable. (Hardware resources, services and projects configurations)

One use is needing to connect signals from low level nodes to UI. Having an auto load (singleton) that can provide a global API can easily get you connected to the UI.

Other reasons can relate to hardware and services and configurations. Godot has many global singletons: Input, InputMap, Rendering, Physics, Engine mainloop, etc.