So I’m working on a basic word game where you’re dealt a “hand” (a dictionary object) of letters that you use to create words and get points.
This “hand” is used in the parameters of a number of functions: calculating a player’s score, updating the number of letters in a hand after a player has used one or more letters, displaying the hand, checking the validity of the player’s word, etc.
From all that I’ve read, I know that I should avoid global variables if I can (though I’m still not totally sure why).
So what other general approach could I use for a number of functions that use “hand” as a parameter?
It’s called an object. Create a class with the shared state, and the functions that share that state.
The reason why this is better than global variables is that it’s a much more restricted version of the same concept – you can clearly see which functions are manipulating those variables, and document (and enforce) the expected invariants on those variables. With global variables it ends up being quite easy to have functions which have different expectations about the state of the shared variables.
It also allows you to have multiple copies of the same object, so instead of having to cast your variables as collections, and correlate between members of the collection, you have a collection of objects, which makes your code simpler. It is then a simple matter to manipulate those objects only through the functions you have defined.