简体   繁体   中英

Best Practices Using Global Variables or Passing Method Arguments to Method Variables?

In the past few months I have been focusing on cleaning up my code for readability purposes. As my app gets larger, it's critical that I have a handle on my variables, classes, methods, etc.

This being said, I often question my decision to create a global variable as opposed to pass a method argument and create a method variable. I find creating local method variables cleans up the remainder of my code by "hiding the overhead", however, I find there is a trade off having to trace and understand the flow of passing method arguments.

Ultimately I believe the best practice comes down to creating minimal overhead by initializing variables at as low a level as possible, essentially:

  • One should only use global variables where the variable is required in multiple methods.
  • One should use a method argument and a method variable where the variable is only required in said method and hence is local to said method.

Is that the simple logical way to approach global vs. method variables? Any advice on this line of thought would be much appreciated. As my code begins to grow into hundreds of methods I need to take more care to create my variables in the most logical way.

Thank you for your advice!

Using global variables is considered bad programming practice in most programming languages that I know. You should use params whenever possible. If at all you need something like the singleton pattern.

If you want to store some global thing you should extend Application class, it some kind of session in Android. In this class you can store everything global.

And don't use singleton, it's a bad practice in Android, use Application class.

This is not an easy question to answer in a few sentences. Use of global variables is a bad practice. It leads to tightly coupled code and makes it very difficult to modify or enhance. The need for large numbers of global variables is an indicator that you need to focus on your design.

You mention your code having hundreds of methods. How many classes do you have? If you have hundreds of methods in a single class, that one class has way too many responsibilities. Your design should focus on having classes with clear responsibilities. Each class should have only the data that it needs for handling those responsibilities. This in turn will lead to a reduction in the number of global variables. If the data is clearly the responsibility of one class then it shouldn't be global and accessible to other classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM