Reputation: 49
Lets say I have 4 conditions, if LEFT, if RIGHT, if DOWN, if UP.
I have a theoretical pawn with X and Y coordinates.
if (LEFT)
{
X--;
}
else if (RIGHT)
{
X++;
}
else if (UP)
{
Y++;
}
else
{
Y--;
}
This is simple enough although I cant imagine its optimal in any setting. Now, what if moving my pawn is harder than simply increment values.
if (LEFT)
{
for (int i = 0; i < 100; i++)
{
// Nice cool algorithm
}
}
else if (RIGHT)
{
for (int i = 0; i < 100; i++)
{
// Nice cool algorithm
}
}
else if (UP)
{
for (int i = 0; i < 100; i++)
{
// Nice cool algorithm
}
}
else
{
for (int i = 0; i < 100; i++)
{
// Nice cool algorithm
}
}
Now obviously this is just plain bad coding right here. copy and paste essentially. So ultimately, my question is this, what aspect of C++ am I missing here? Is there a way to "interchange operators" like when the condition is LEFT the operator changes to "--" on the X and when its RIGHT it changes to "++".
Maybe I can store a operator as a variable somehow so the operations are on one line and one version of an algorithm is written,
X << OPERATORvariable
That's the best I can do to ask this question. Feel free to tell me im in the wrong place to ask this or that I dont know squat about programming :)
Upvotes: 0
Views: 67
Reputation: 206607
Now obviously this is just plain bad coding right here. copy and paste essentially.
Possibly but you can only simplify so much.
You cannot remove the check for the four conditions.
If all you do for those conditions is increment/decrement X and Y, I wouldn't sweat too much. At best, you could abstract out what happens under those conditions to four functions.
if (LEFT)
{
moveLeft();
}
else if (RIGHT)
{
moveRight();
}
else if (UP)
{
moveUp();
}
else
{
moveDown();
}
If you have to loop over some variables in each of those functions, you can abstract out that operation to another function.
For example:
void doSomethingForEachItem(void (*fun)(...)))
{
for (int i = 0; i < 100; i++)
{
// Call fun for each item
}
}
void moveLeft()
{
doSomethingForEachItem(moveLeftFunction);
}
Upvotes: 1