【问题标题】:How to avoid passing "redundant" arguments in function?如何避免在函数中传递“冗余”参数?
【发布时间】:2020-09-10 20:27:45
【问题描述】:

我正在编写一些代码,我意识到当函数不使用参数时,我一直在向函数传递参数。只有具有功能的子功能(或子功能内的子功能等......)使用它。

实际的函数根本没有使用参数,它的唯一目的是将参数“中继”到子函数(或子子函数等)

例如:

int search(int (*board)[DIM],int search_digit,int * bestRow,int *bestCol)
{ 
  //some code,haven't use arguments bestRow,bestCol

  longest=seq_length( board,longest,search_digit,bestRow,bestCol,r,c); //sub-function

  //some code,haven't use arguments bestRow,bestCol
}

int seq_length(int board[][DIM],int longest,int search_digit,int * bestRow,int *bestCol,int row,int col)
{
  //some code,haven't use arguments bestRow,bestCol

  longest=updateLongest_best(bestRow,bestCol,longest,seqLength,row,col); //sub-sub-function

  //some code,haven't use arguments bestRow,bestCol

}

int updateLongest_best(int* bestRow,int *bestCol,int longest,int seqLength,int row,int col)
{ 
 //finally used arguments bestRow,bestCol
}

有没有一种优雅的方式来规避冗余参数的传递?或者这只是 C 的固有部分?

【问题讨论】:

  • 我会说你需要重构代码来扁平化调用树,但是没有real code就很难说了。
  • 我会说,如果需要将参数传递给子函数......这不是多余的!现在,bestRowbestColsearch() 返回的指针。真正的问题是:search() 的调用者是否使用或设置了这些参数?如果是,你就完成了。
  • “显而易见”的替代方法是通过全局变量“传递”这些变量。这不是(即NOT)是个好主意——编写的代码更好。如果你有两个或更多这样的参数(如这里),你可以考虑将它们组合成一个通过指针传递的结构,这样只有一个直接参数。
  • @RobertoCaboni 你是说只要search()的调用者使用上面提到的那些参数,就没有多余的
  • @JonathanLeffler 我可以在这里使用结构,谢谢!

标签: c function parameters arguments


【解决方案1】:

将我的comment 转换为答案。

“显而易见”的替代方法是通过全局变量“传递”这些变量。这不是(重复,不是)是个好主意——编写的代码更好。

如果您有两个或多个参数从一个函数传递到另一个函数(如此处),您可以考虑将它们组合成一个通过指针传递的结构,这样每个被调用函数只有一个直接参数。

请注意,如果从子函数调用的函数需要用户传递给调用函数的信息,则参数不是“冗余”;它们是必要的,即使是冗长的。

大纲:

typedef struct BestInfo
{
    int row;
    int col;
} BestInfo;

int search(int (*board)[DIM], int search_digit, BestInfo *best)
{ 
    // some code; doesn't use argument best

    longest=seq_length(board, longest, search_digit, best,  r, c); //sub-function

    // some more code; doesn't use argument best
}

int seq_length(int board[][DIM], int longest, int search_digit, BestInfo *best, int row, int col)
{
    // code that doesn't use argument best

    longest = updateLongest_best(best, longest, seqLength, row, col); //sub-sub-function

    // more code that doesn't use argument best
    return …;
}

int updateLongest_best(BestInfo *best, int longest, int seqLength, int row, int col)
{ 
    // Finally use argument best: best->row, best->col
    // You can split the structure when appropriate
    int r1 = one_more_function(&best->row);
    int r2 = another_function(&best->col);
    return computation_using(r1, r2);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2019-01-02
    • 1970-01-01
    • 2014-04-08
    相关资源
    最近更新 更多