Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it's not ok for variables to be global but it's ok for functions?

I was writing some Python code and, as usual, I try to make my functions small and give them a clear name (although sometimes a little too long). I get to the point where there are no global variables and everything a function needs is passed to it.

But I thought, in this case, every function has access to any other function. Why not limit their access to other functions just like we limit the access to other variables.

I was thinking to use nested functions but that implies closures and that's even worse for my purpose.

I was also thinking about using objects and I think this is the point of OOP, although it'll be a little too much boilerplate in my case.

Has anyone got this problem on her/his mind and what's the solution.

like image 229
nicusor Avatar asked Mar 07 '16 18:03

nicusor


2 Answers

It is not a good idea to have global mutable data, e.g. variables. The mutability is the key here. You can have constants and functions to your hearts content.

But as soon as you write functions that rely on globally mutable state it limits the reusability of your functions - they're always bound to that one shared state.

like image 173

For the sake of everyone reading your code, grouping the functions into classes will help to mentally categorize them. Using the class self parameter helps to organize the variables, too, by grouping them in a class.

You can limit their access with a single leading underscore at the beginning of the function name.

like image 37
Brent Washburne Avatar answered Sep 28 '22 15:09

Brent Washburne