cdrynamespace-organisation

Dry out this code snippet (without dirtying up the namespace too much)


I had

for (i = 1; i < max_i; i++) {
  e[i] == 1 ? printf("%ld", p[i]) : printf("%ld^%ld", p[i], e[i]);
}

in a loop, but then needed to write multiplication signs between the elements (but not the first). I didn't want

e[1] == 1 ? printf("%ld", p[1]) : printf("%ld^%ld", p[1], e[1]);
for (i = 2; i < max_i; i++) {
  e[i] == 1 ? printf(" * %ld", p[i]) : printf(" * %ld^%ld", p[i], e[i]);
}

so I write a quick, one-time function

void
show_pe(int p, int e)
{
    if (e == 1)
        printf("%ld", p);
    else
        printf("%ld^%ld", p, e);
}

which, despite dirtying up the namespace, removed the duplication nicely. But now I see that the following functions have similar code not covered by my quick function. I'd need

void
show_e_p(int p, int e)
{
    if (e == 1)
        printf("%ld", p);
    else
        printf("%ld*%ld", e, p);
}

and

void
show_pe_outside(int p, int e)
{
    if (e == 1)
        printf("a(%ld)", p);
    else
        printf("a(%ld)^%ld", p, e);
}

and a host of others. But since these would only be used twice each, two lines apart, this seems wasteful (and separates code from its natural place, rarely a good thing). Surely there's a better way! Ideas?


Solution

  • Hint:

    do {
      code block to be executed
    } while (condition);
    

    ie - consider changing your loops so that the duplicated code is not duplicated anymore..