C
C#2y ago
Google

❔ How do I make these two codes less copy pasta?

void Redo()
{
var thingToUnreverse = Actions[CurrentActionStep + 1];
foreach (var thing in thingToUnreverse.thingsMoved)
{
var bvmToMove = objectCollection.FirstOrDefault(bvm => bvm.Guid == thing.objectViewModel.Guid);
if (bvmToMove is null) { continue; }
bvmToMove.Position = thing.NewPosition;
} //There are also a dozen other operations that occur here.
}

void Undo()
{
var thingToReverse = Actions[CurrentActionStep];
foreach (var thing in thingToReverse.thingsMoved)
{
var bvmToMove = objectCollection.FirstOrDefault(bvm => bvm.Guid == thing.objectViewModel.Guid);
if (bvmToMove is null) { continue; }
bvmToMove.Position = thing.OldPosition;
}
}
void Redo()
{
var thingToUnreverse = Actions[CurrentActionStep + 1];
foreach (var thing in thingToUnreverse.thingsMoved)
{
var bvmToMove = objectCollection.FirstOrDefault(bvm => bvm.Guid == thing.objectViewModel.Guid);
if (bvmToMove is null) { continue; }
bvmToMove.Position = thing.NewPosition;
} //There are also a dozen other operations that occur here.
}

void Undo()
{
var thingToReverse = Actions[CurrentActionStep];
foreach (var thing in thingToReverse.thingsMoved)
{
var bvmToMove = objectCollection.FirstOrDefault(bvm => bvm.Guid == thing.objectViewModel.Guid);
if (bvmToMove is null) { continue; }
bvmToMove.Position = thing.OldPosition;
}
}
Looking for a way to combine these two to more share code so I don't have to update each every time.
9 Replies
Jimmacle
Jimmacle2y ago
would it be too ugly to add a bool selector to one of the methods and have the other method call it with the flag set? alternatively factor it into a separate method and pass in the "thing" or the array offset and a Func<Thing, Position> for the position source
Google
GoogleOP2y ago
Func might be the way to go.
Servator
Servator2y ago
Just pass a argument for +1 and call Undo() or Redo() from Undo() or redo()
Google
GoogleOP2y ago
thing.OldPosition vs thing.NewPosition
Servator
Servator2y ago
void Redo(int someShit)
{
return Undo(someShit);
}
void Redo(int someShit)
{
return Undo(someShit);
}
hmm You can change that to into a switch too or if
Google
GoogleOP2y ago
that just moves the problem from 2 methods to 1 method with a bunch of switch statements.
Anton
Anton2y ago
yeah you're gonna have either a check or a virtual method call somewhere func or interface will do the latter, which is going to be a bit slower than a check you could also do a x * thing.old + (1 - x) * thing.new and pass in either a zero or a one, but I think the compiler should see this one through if you go with a check
Google
GoogleOP2y ago
Just went with an Action.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server