简体   繁体   中英

Best practice for accessing command line arguments globally in Java

What's the best way to store a global setting passed to a Java program from the command line? for example if you were to run >Java myProgram -verbose I want to be able to know whether or not verbose was specified in all the private functions. It feels wrong to add five or ten parameters to every function just to pass the necessary variables along, but I've also been reading that global variables in Java are the work of the devil, even if they are only set once. This must be an extremely common issue but I haven't been able to find anything that explains the best way to deal with it and I'd appreciate if someone can point me in the right direction.

Global Variables are never the work of the devil in any language. Instead, they're more like a rubix cube.

If you know the absolute best ways to use them, you'll rarely run into a problem you can't solve. If you know the basic ways to use them, you'll get through it, but it will take a while to get everything to line up right. If you don't know how to use them, they'll just make for a pretty collection of colored squares...

The thing to keep in mind is that most times you need to use a global variable, you could instead use with dependency injection. It will have less bugs and probably yield the same results. The code will also be cleaner, which is always good.

Instead of adding 10 variables to your methods, why not add those variables to your class? Why not store them inside their own container so they're grouped logically?

For more information and implementation, I'd need to see more background.

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