程序中如何处理参数?
这是一个高级问题,我确信没有普遍正确的答案,但我真的很想了解更多有关执行此操作的不同方法的信息:
如何最好地处理程序中的参数?
为了澄清,我正在谈论程序执行某些任务所需的所有值(例如,类变量的值)。在许多情况下,人们希望在不同的场景中使用不同的值。那么如何最好地处理这些(用户提供的)值呢?
一些方法:
- 只需在代码中定义它们并根据需要更改它们(即, 更改源代码)
- 使用特殊的类来指定所有参数并使用静态导入使用
- 指定的所有参数实现接口(并相应地实现接口)
- 将它们作为命令行参数传递
- 使用(文本)文件并加载它们(使用,例如,加载后访问值的类)
我知道其中一些是不好的做法,所以请根据您的经验列出优点和缺点。
This is a high-level question and I am sure there is no universally correct answer but I really would like to learn more about the different ways of doing this:
How does one best deal with parameters in a program?
To clarify, I am talking about all the values (e.g., of class variables) that the program requires to execute certain tasks. In many cases, one would like to use different values in different scenarios. So how to best deal with these (user-supplied) value?
Some approaches:
- Simply define them in the code and change them as required (i.e.,
change source code) - Use a special class to specify all parameters and use static imports
- Implement an interface with all the parameters specified (and implement interface accordingly)
- Pass them as command line arguments
- Use a (text) file and load them (using, e.g., a class to access the values after loading)
I know that some of these are bad practice so please also list the pros and cons based on your experience.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我只会在源中放入从未改变的实常量。由于新的输入而必须重建程序并不是真正必要的
另一个选项是通过选项或参数(命令行或 GUI)使它们可用
如果您的用例几乎每次使用程序时都需要不同的参数,请选择命令行选项(具有可选的默认值)。这将迫使用户思考它们
如果参数很少更改,请使用选项存储(文本文件、xml 文件、数据库,无论最适合什么)
I would put in the sources only real constants that are never changed. Having to rebuild a program because of a new input is not really necessary
The other option is to make them available with options or arguments (command line or GUI)
If your use case requires different arguments almost every time you use your program choose the command line option (with optional defaults). This will force the user to think about them
If the parameters rarely change use an option storage (text file, xml file, database whatever is best suited)