How to write clean code if you need to do the same code for different circumstances

So im coding a thing in minecraft and and i need to check if the player is facing North, West, South or East. And i need to loop the blocks to that direction. What would be the best solution if i just do this its gonna be really messy.

    if (direction.equals(EnumFacing.NORTH)) {         for (int i = 0; i < 5; i++) {         //Loop blocks in North direction         }     } else if (direction.equals(EnumFacing.WEST)) {         for (int i = 0; i < 5; i++) {         //Loop blocks in West direction         }     } else if (direction.equals(EnumFacing.EAST)) {         for (int i = 0; i < 5; i++) {         //Loop blocks in East direction         }     } else if (direction.equals(EnumFacing.SOUTH)) {         for (int i = 0; i < 5; i++) {         //Loop blocks in South direction         }     } 

So yeah as you can see the code gets really messy. So what would be the best solution to do this so it would stay somewhat clean?

Add Comment
1 Answer(s)

You can try this: just have the loop and then do a switch case inside it.

I would also create a method that you pass the direction to that handles the movement code. If you do that, then the switch case should be inside that instead of the loop, like so:

for(int i = 0; i < 5; i++) {   DoPlayerMovement(direction); }  DoPlayerMovement(EnumFacing direction) {    switch(direction) {      case EnumFacing.NORTH: **YOUR CODE HERE**; break;      case EnumFacing.SOUTH: **YOUR CODE HERE**; break;      case EnumFacing.EAST: **YOUR CODE HERE**; break;      case EnumFacing.WEST: **YOUR CODE HERE**; break;    } } 

For more information on switches, check out the official Java tutorial here.

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.