Scope of variables recognition


#1

In 11. Making a Purchase exercise I used the prices dictionary in the compute_bill function. I tested it outside the OL tool and it worked. This means that the dictionary (prices) which is defined in the main program is recognized inside a function (not being transferred as an argument).
I was very surprised by this finding since it is not considered a good programming practice.
Any comments?


#2

Hello, @ruok987!
As you noticed, at any part of your code you'll be able to access and alter the values in that same dictionary which means that structure is "global".
Is nice? Not much due to the fact that global variables, or in this case structures, can be altered by anyone or anything in your code.
Can you imagine a 1.000 entries dictionary being altered by an "evil" function created by a bad person to alter the data inside and cause a huge mess when they try to retrieve the data stored into that dictionary to execute some operations? Trust me, it's really bad and to fix it is quite tiring.

For those examples, being "global" won't really be a problem but know that whenever you're working with something, make sure to avoid such globals.
You'll save your time and your team's time.

Quote me if there's anything else I can help you with!

Best regards,
g4be