Juan Estevez
Juan Estevez

Reputation: 866

Avoid global variables but keep code easy to understand

The following code includes some classes and functions.

def other_funcs(*args):
    # uses Roll and RollSet a lot
    pass

The code makes use of global variables to hold some parameter values.
I understand this is very bad practice and can cause many problems but it has the following desirable property:
It keeps the number of arguments for the defined classes and functions to a minimum and makes the code a lot easier to read and understand.

I have tried using a container class but I end up having to pass it's instance as an argument to every other function/class like RollSet(rolls, param.roll_extra_width) instead of just RollSet(rolls). This seems unnecessarily redundant since the parameters will always remain unchanged after initialization.

Can someone please suggest a better way to hold the parameter values without cluttering the code with long argument lists and repeated arguments?

Upvotes: 3

Views: 151

Answers (2)

JL Peyret
JL Peyret

Reputation: 12204

I don't see anything particularly wrong with

roll_extra_width = 2
max_roll_count = 5

they are essentially constants in your code and you did a proper job declaring them at the top of the module rather than sprinkling them throughout your code, aka the Magic Numbers antipattern. BTW, magic strings are a thing too: if objecttype == "customer":

However, if they are constants, you might as well capitalize them, that is the usual convention in those cases.

ROLL_EXTRA_WIDTH = 2
MAX_ROLL_COUNT = 5

Also, a huge part of the global variable concern has to do with shared global state on mutable variables. These are, immutable, integers, so not a big worry here.

If you have tons of constants like this, you might want to shunt them off into a constants.py or the like because they will clutter up your code otherwise. That's a matter of preference, other people may have other, better, suggestions.

Upvotes: 1

Siddarth Raghuvanshi
Siddarth Raghuvanshi

Reputation: 127

First of all, I just want to mention that just because global variables are bad doesn't mean that there isn't a place for them. It's up to you to decide if you're willing to accept the downsides.

A container class is a great idea, and that's generally what I would use. In your particular case looking at the code, I would initialize roll_extra_width and max_roll_count within the classes RollSet and Roll. Looking at your code these are the only places where the variables are used and these classes are the ones being called repeatedly, and not the actual global variables.

Here's an example to make it more clear:

class RollSet(Counter):
    def __init__(self):
        roll_extra_width = 2
        max_roll_count = 5

Hope that helps !

Upvotes: 2

Related Questions