Tell me, please, is it possible to replace Iterator somehow with Stream. If not, then you can somehow shorten the code:

private boolean moveMan(Direction direction){ int numberCollisionWithWalls=0; Iterator<Man> iterator = mans.iterator(); while (iterator.hasNext()) { Man man = iterator.next(); Position oneStep = direction.next(man.getPosition()); GameObject gameObject = new GameObject(oneStep.getX(), oneStep.getY()); if (walls.contains(gameObject)) { numberCollisionWithWalls++; continue; } if (badWalls.contains(gameObject)) { gameOver(); return false; } Position twoStep = direction.next(oneStep); if (mans.contains(gameObject)&& walls.contains(new GameObject(twoStep.getX(), twoStep.getY()))) { gameOver(); return false; } if (getTarget().equals(gameObject)) { iterator.remove(); continue; } man.setPosition(oneStep); } if(numberCollisionWithWalls!=mans.size()) { numbertStep++; } return true; } 
  • one
    Streams are not needed here, you have continuous side effects in the code. - Nofate
  • Or maybe you can somehow improve the code? - desking
  • one
    Yes, he is not bad in principle. - Nofate
  • two if'a, which initialize gameOver - probably and can be combined - Alexey Shimansky

1 answer 1

If your goal is to increase the readability of a code, then refer to Robert Martin’s Clean Code book, namely Chapter 3. Functions.

Update:

To improve readability, it is recommended to strive for the rule of one operation. For example, you can organize the code as:

 private boolean moveMen(Direction direction) { Iterator<Man> iterator mans.iterator(); while (iterator.hasNext()) { Man man = iterator.next(); Position oneStep = direction.next(man.getPosition()); Man manOnNextStep = (Man) new GameObject(oneStep.getX(), oneStep.getY()); updateCollisionWithWalls(manOnNextStep); if(isGameOverForMan(manOnNextStep)) return false; if (manOnNextStep.equals(getTarget())) iterator.remove(); man.setPosition(oneStep); } return true; } 

And improve until you start to like the result.

  • 2
    This is a comment rather than an answer. - Denis
  • one
    @Denis: I'll keep it in mind. Just started to settle down on the site, at the time of the answer could not yet leave comments. - Victor Borovlev
  • With your rating, in my opinion, you can already afford it :) - Denis