Change operator + by - in refactored method

0

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 )

    
asked by anonymous 02.02.2016 / 17:55

1 answer

3

Apply your algebra knowledge:

  

x + y = x + (1) * and
  x - y = x + (-1) * y

Create a new method and place this repeated code on it, use the one that has the + sign and multiply the (initialMousePosition.y - mousePosition3D.y) section by the value passed to the method.

Call this method by passing 1 or -1 depending on whether you want to add or subtract.

private void SwipeContainer(Directions direction){
    if(direction == Directions.Top && transform.localPosition.y < maxTopPosition){
        movimenta(1);
    }else if(direction == Directions.Bottom && transform.localPosition.y > maxBottomPosition){
        movimenta(-1);
    }
}

private void movimenta(int direcao){
    Vector3 position = Input.mousePosition;

    Vector3 mousePosition3D = Camera.main.ScreenToWorldPoint(position);
    mousePosition3D.z = -1f;
    mousePosition3D.x = transform.position.x;
    mousePosition3D.y = transform.position.y + direcao * (initialMousePosition.y - mousePosition3D.y);

    transform.position = Vector3.MoveTowards(
        transform.position, mousePosition3D, speedMoviment * Time.deltaTime
    );
}
    
02.02.2016 / 18:36