Refactoring Example
Original Code
(worms game)
op = &(!x ? (!y ? upleft : (y == bottom ? lowleft : left)) :
(x == last ? (!y ? upright : (y == bottom ? lowright : right)) :
(!y ? upper : (y == bottom ? lower : normal))))[w->orientation];
What is going one here?
More Readable Representation
(Formatted as cascading if-else)
op = &(
!x ? (
!y ?
upleft
: ( y == bottom ?
lowleft
:
left
)
) : ( x == last ? (
!y ?
upright
: ( y == bottom ?
lowright
:
right
)
) : (
!y ?
upper
: ( y == bottom ?
lower
:
normal
)
)
))[w->orientation];
Re-implementation
struct options *locations[3][3] = {
{upleft, upper, upright},
{left, normal, right},
{lowleft, lower, lowright},
};
int xlocation, ylocation;
if (x == 0)
xlocation = 0;
else if (x == last)
xlocation = 2;
else
xlocation = 1;
if (y == 0)
ylocation = 0;
else if (y == bottom)
ylocation = 2;
else
ylocation = 1;
op = &(locations[ylocation][xlocation])[w];
Other Implementation
(Suggested by Guy Steele)
op =
&( !y ? (!x ? upleft : x!=last ? upper : upright ) :
y!=bottom ? (!x ? left : x!=last ? normal : right ) :
(!x ? lowleft : x!=last ? lower : lowright )
)[w->orientation];