When working with a modular game structure, is it bad practice to supply variables to other modules upon intialization?
For example:
PlayerController
local CharacterController = require(script.CharacterController)
local localPlayer = Players.LocalPlayer
local PlayerController = {}
function PlayerController:init()
CharacterController:init(localPlayer)
end
This is just an example, but in this case, is it better for the characterController to handle the player variable by itself?
No, that’s alright, you can have modules that require other modules to work, it just keeps everything more tidy I guess. These modules can basically act as helpers for your main module that you require in your main script.
So, it’s not bad practice, though overdoing it will definitely make the whole hierarchy and the scripts more confusing.
What you’re doing seems to be very similar to dependency injection. Generally speaking, it’s better to make implicit factors like ‘who is the local player’ or ‘what is the server time’ into explicit parameters, because it makes your code easier to reason with and test.
I’d actually argue you should move localPlayer higher and make the consumer of the PlayerController have to pass it in. That way, you could theoretically pass in a different player or a mock object to do unit testing with.
I think this can be answered by a very simple question. Do I need the ability to overwrite the player object with something else, or does getting the right player object require a lot of complexity best managed by something else?
If the answer is yes, inject it. If the answer is no, then don’t inject it. Ultimately you want your scripts to be as easy to work with as possible and small, superfluous injections will add up over time (I’ve had to work with some systems where literally every subsystem wanted player for example and now every single thing down this whole tree is being passed player when only the stuff that actually needed it could have just queried it itself).
There are good reasons for doing so though, hence the question.
Yeah, I realised that if my modules rely on stuff from other modules like this then over time as I expand it’ll get messy so for now I just have a main module and then a branch of other ‘main’ modules that handle stuff themselves and inside of those ones I have sort of utility modules that can get the supplied variables to them if needed. Etc but I think I have a good structure going for my game right now, thanks