在 Java 中全局访问命令行参数的最佳实践
存储从命令行传递给 Java 程序的全局设置的最佳方法是什么?例如,如果您要运行 >Java myProgram -verbose
我希望能够知道是否在所有私有函数中指定了 verbose。仅仅为了传递必要的变量而向每个函数添加五个或十个参数感觉是错误的,但我也读到 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在任何语言中,全局变量都不是魔鬼的杰作。相反,它们更像是魔方。
如果您知道使用它们的绝对最佳方法,那么您很少会遇到无法解决的问题。如果您知道使用它们的基本方法,您就会完成它,但需要一段时间才能使所有内容都正确排列。如果您不知道如何使用它们,它们只会形成漂亮的彩色方块集合...
要记住的是,大多数时候您需要使用全局变量,您可以改为与依赖注入一起使用。它的错误会更少,并且可能会产生相同的结果。代码也会更加清晰,这总是好的。
为什么不将这些变量添加到您的类中,而不是向您的方法添加 10 个变量呢?为什么不将它们存储在自己的容器中,以便按逻辑分组?
有关更多信息和实施,我需要查看更多背景。
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.
使用上下文对象模式。
Use the context object pattern.