Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to use local or global variables

Is it better to use local or global variables?

Let's say talking about 2000+ lines of android(java) service class, and all service is working on 'request' object and similar shared objects.

If I make everything local(keep inside of function), I need to pass many variables every time, or override same function many times. I need to make sure that objects, and sub objects are not null too.

If I make some variables global(across the class) I can share them, use them across the functions. Which I think will make everything easier.

What are the good sides and bad sides of defining variables inside of function or defining globally. In practice, and in theory(readability etc).

Is there suggested way?

Thank you.

like image 403
Mohamed Avatar asked Jul 24 '17 23:07

Mohamed


1 Answers

Always prefer local over global. If you need to pass the data in as multiple parameters, so be it. At least then you're explicitly saying what data your function depends on. Having too many parameters is certainly a problem, but offloading some of them as globals isn't the answer.

If you rely on globals, it may not be as clear where certain data is coming from. If the globals are mutable, you'll have a mess on your hands as soon as you start to try to debug a difficult problem since it may not be obvious when certain global variables are being modified.

Note though that immutable constant globals aren't bad. If you have a constant that's needed in many functions (like PI for example), it makes sense to make it global. Immutable constants don't suffer from the drawbacks mentioned above since they can't change.

like image 174
Carcigenicate Avatar answered Sep 22 '22 16:09

Carcigenicate