Refactoring to make it DRY

I didn’t really like having two functions that did basically the same thing, just in opposite directions, so I refactored to make it into a single function.

void UOpenDoor::MoveDoor(float DeltaTime, bool Open)
{
	float DoorDirection;
	float DoorSpeed = DoorCloseSpeed;
	DoorDirection = OriginalRotation.Yaw;

	if (Open) {
		DoorDirection = TargetYaw;
		DoorSpeed = DoorOpenSpeed;
	}

	CurrentYaw = FMath::FInterpTo(CurrentYaw, DoorDirection, DeltaTime, DoorSpeed);
	FRotator DoorRotation = OriginalRotation;
	DoorRotation.Yaw = CurrentYaw;
	
	GetOwner()->SetActorRotation(DoorRotation);
}

By default the door is closed, until it is opened.
Then I decided that with this setup, it would be really easy to add a few more lines to change the door speed based off of the door opening or closing, and added that to my header file.

UPROPERTY(EditAnywhere)
float DoorOpenSpeed = 1.3f;

UPROPERTY(EditAnywhere)
float DoorCloseSpeed = 5.f;

I actually like a few other implementations people have posted where they sent the targetYaw to their function instead of a Boolean because this means that the target could be variable in multiple ways and gives the door more states than just opening or closing, but I’m happy with this for now.

It took a bit to figure out how to refactor my logic tree so that they were more DRY as well, but this is what I came up with.

if (ComponentsSet) 
{
	if (PressurePlate->IsOverlappingActor(ActorThatOpens))
	{
		MoveDoor(DeltaTime, true);
	}
	else
	{
		MoveDoor(DeltaTime, false);
	}
}

I had some difficulty at first because I don’t want either function to fire unless Components are set so that nothing breaks, although now that I think about that, it probably doesn’t matter. This should work for future proofing though because ActorThatOpens can be called from the MoveDoor function directly, and this should prevent crashes in case someone like that weird case happens.

1 Like

Keep up the great work. DRY is really important.

Privacy & Terms