How to avoid excessive parameter passing?

后端 未结 6 846
予麋鹿
予麋鹿 2021-02-11 00:22

I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These opt

6条回答
  •  梦如初夏
    2021-02-11 00:51

    [Caution: my answer isn't specific to python.]

    I remember that Code Complete called this kind of parameter a "tramp parameter". Googling for "tramp parameter" doesn't return many results, however.

    Some alternatives to tramp parameters might include:

    • Put the data in a global variable
    • Put the data in a static variable of a class (similar to global data)
    • Put the data in an instance variable of a class
    • Pseudo-global variable: hidden behind a singleton, or some dependency injection mechanism

    Personally, I don't mind a tramp parameter as long as there's no more than one; i.e. your example is OK for me, but I wouldn't like ...

    import a
    p1 = some_command_line_argument_value
    p2 = another_command_line_argument_value
    p3 = a_further_command_line_argument_value
    a.meth1(p1, p2, p3)
    

    ... instead I'd prefer ...

    import a
    p = several_command_line_argument_values
    a.meth1(p)
    

    ... because if meth2 decides that it wants more data than before, I'd prefer if it could extract this extra data from the original parameter which it's already being passed, so that I don't need to edit meth1.

提交回复
热议问题