November 2024
Intermediate to advanced
300 pages
7h 12m
English
An impure function creates side effects. The prototypical side effect: you call a void method that changes the value of one or more fields in the containing object. The Location class does just that in its move method (highlighted):
| | import java.util.Objects; |
| | |
| | public class Location { |
| | enum Heading {North, East, South, West} |
| | private int x, y; |
| | private Heading heading; |
| | |
| | public Location(int x, int y, Heading heading) { |
| | this.x = x; |
| | this.y = y; |
| | this.heading = heading; |
| | } |
| | |
| » | public void move(int distance) { |
| » | switch (heading) { |
| » | case North -> y = y + distance; |
| » | case East -> x = x + distance; |
| » | case South -> y = y - distance; ... |
Read now
Unlock full access