fliX
fliX

Reputation: 813

Reduce code duplication

I have two functions that differ only in one parameter (different struct) that nearly do the same processing resulting in a lot of duplication of code. See the following simplified example:

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
}

Is there some smart way in using only one function eliminating the code duplication?

Upvotes: 2

Views: 124

Answers (1)

2501
2501

Reputation: 25753

Yes there is, but not in a way you imagine. Keeping type safety is really beneficial and it isn't in your best interest to get rid of it (either using pointers to void or struct interitance).

If you have two different types that are defined as separate types for some meaningful reason, then you should have two separate functions that take those types.

What you should do in this case, is to remove the duplication inside those functions:

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 );
}

Upvotes: 4

Related Questions