The code below is intended to make a move on an object on the Y axis of an object following the mouse (the code works), see that the code inside if
and else if
are the same as not and - operator - what would be the ways to refactor this duplicate code by changing only the operators in the line (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 only apply to this language ( C # ) and specific situation, what would be the appropriate forms of refactoring (applicable to most languages like: C # Java, PHP, Javascript, C )