let's say I have:
switch( choice ) {
case A:
stmt;
do_stmt_related2A;
break;
case B:
stmt;
do_stmt_related2B;
break;
case C: something_different();
...
}
How could I avoid duplicating stmt code?
But is there any workaround? gcc extension label as value looks quite good for such situation.
switch( choice ) {
do {
case A: ptr = &&A_label;
break;
case B: ptr = &&B_label;
} while(0);
stmt;
goto *ptr;
case C: ...
Is there any trick that can do the same in ANSI-C? Edit: Of course I have thought of function/macro/inline. But anything else? It's not about performance either. Just for educational purpose. ;)
The conventional approach to reduce this kind of code duplication is to move the common code to a member function, which can be called from all the constructors. Usually, that member function is called init.
As structural code duplication is usually obvious and easy to eliminate, semantic duplication is often left behind due to the lack of ideas or knowledge on how to eliminate it. However, there is one key concept that will solve all semantic code duplication (as well as structural duplication), namely “abstraction”.
It's safe to say that duplicate code makes your code awfully hard to maintain. It makes your codebase unnecessary large and adds extra technical debt. On top of that, writing duplicate code is a waste of time that could have been better spent.
In computer programming, duplicate code is a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity.
Why don't you just refactor stmt
(I'm assuming this is a big chunk of instructions rather than a single line) into its own function do_stmt()
and call it? Something like:
switch( choice ) {
case A:
do_stmt();
do_stmt_related2A;
break;
case B:
do_stmt();
do_stmt_related2B;
break;
case C: something_different();
...
}
That gcc trick is truly hideous. I would rather have readable code over such monstrosities any day.
You should always assume that the programmer that inherits your code is a homicidal maniac who knows where you live :-)
How could I avoid duplicating stmt code?
By putting it into a function and call that.
And, no, you do not know whether this will slow down your application until you profiled it and found it to be the bottleneck. (And in case it really is, use a macro or, if that's C99, make the function inline
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With