【问题标题】:Reduce code duplication减少代码重复
【发布时间】:2016-08-21 18:14:13
【问题描述】:

我有两个函数,它们仅在一个参数(不同的结构)上有所不同,它们几乎执行相同的处理,导致大量重复代码。请参见以下简化示例:

struct foo {
    int a;
};

struct bar {
    int a;
    int b;
};

foo(struct foo *f) {
    do_b();
    // error handling
    f->a = 1;
    do_c();
    // error handling
    do_d();
    // error handling
}

bar(struct bar *b); {
    do_a();
    // error handling
    b->b = 2;
    do_b();
    // error handling
    b->a = 1;
    do_c();
    // error handling
    do_d();
    // error handling
}

是否有一些聪明的方法可以只使用一个函数来消除代码重复?

【问题讨论】:

  • 你愿意把struct B改成struct B { struct A a; int b; };吗?
  • 真正聪明的方法需要你完全理解strict aliasing rule。不幸的是,没有人理解这条规则(exampleexampleexample)。所以你有点卡住了。

标签: c optimization


【解决方案1】:

是的,但不是你想象的那样。保持类型安全确实是有益的,摆脱它并不符合您的最佳利益(使用指向 void 的指针或结构交互)。

如果出于某种有意义的原因将两种不同的类型定义为单独的类型,那么您应该有两个单独的函数来接受这些类型。

在这种情况下你应该做的是删除这些函数中的重复:

first( int* a )
{
   do_b();
    // error handling
    *a = 1;
    do_c();
    // error handling
    do_d();
    // error handling
}

foo(struct foo *f) {
    first( &f->a );
}

bar(struct bar *b); {
    do_a();
    // error handling
    b->b = 2;
    first( &b->a );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2016-07-24
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多