0
The Code below has the goal of making a move on an object on the Y axis of an object following the mouse (the code works), see that the code within the if
and of else if
are equal except by the operator + and - what would be the ways to refactor this duplicate code by changing only the line operators (only what is in bold):
mousePosition3D.y = Transform.position. y + (initialMousePosition. y - mousePosition3D.y);
private void SwipeContainer(Directions direction){
if(direction == Directions.Top && transform.localPosition.y < maxTopPosition){
Vector3 position = Input.mousePosition;
Vector3 mousePosition3D = Camera.main.ScreenToWorldPoint(position);
mousePosition3D.z = -1f;
mousePosition3D.x = transform.position.x;
mousePosition3D.y = transform.position.y + (initialMousePosition.y - mousePosition3D.y);
transform.position = Vector3.MoveTowards(
transform.position, mousePosition3D, speedMoviment * Time.deltaTime
);
}else if(direction == Directions.Bottom && transform.localPosition.y > maxBottomPosition){
Vector3 position = Input.mousePosition;
Vector3 mousePosition3D = Camera.main.ScreenToWorldPoint(position);
mousePosition3D.z = -1f;
mousePosition3D.x = transform.position.x;
mousePosition3D.y = transform.position.y - (initialMousePosition.y - mousePosition3D.y);
transform.position = Vector3.MoveTowards(
transform.position, mousePosition3D, speedMoviment * Time.deltaTime
);
}
This refactoring problem does not apply only to this language (C#) and specific situation, what would be the appropriate forms of refactoring (which is applicable to most languages such as: C#, Java, PHP, Javascript, C)
You can check the condition only on the line in question. If you only have these options you can change to a
if else
simple. The way it is he will make the two comparisons, but if he does not meet either of the two he will do nothing.– Randrade