Skip to content

Commit

Permalink
Added example of pattern matching to replace switch
Browse files Browse the repository at this point in the history
  • Loading branch information
matiastripode authored Apr 18, 2020
1 parent 57aa424 commit 999a33c
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
1. Inspired by Jason Gorman in his TDD videos series [Test-Driven Development (TDD) in Python #4 - Duplication & The Rule of Three](https://www.youtube.com/watch?v=f6KHs4aMPpU&list=PL1tIFPlmF4ykpjOJKVDwYkpBIeXsoak6S&index=4)) I decided to follow along his video and implement my own version of Mars Rover Kata.

2. Implemented Mars Rover Kata using Python and following TDD. Kata requirements can be found here https://kata-log.rocks/mars-rover-kata.
3. Takeways
3. Takeaways
3.1 Usage of `@parameterized.expand([])` to parameterized tests. A best practice that can be handy is:
- parameterized should follow `AAA` from left to righ (`Arrange`, `Act`, `Assert`), there could be more than `A`parameter per section. As you can see in the example bellow there are two `Arrange` pre-conditions (`Compass` and `Point`), one Act (`MoveCommand`) and one `Assert` (`Point`)

Expand All @@ -22,6 +22,43 @@
#Assert
self.assertTrue(mars_rover.current_position() == ends_position)
```
3.2 Another takeaway is the usage of dictionaries and pattern matching as awesome replacement for `switch` statements:
```python
def check_boundaries(self, move_command):
return {
(Compass.N, MoveCommand.FORWARD): self._current_position.y > 0,
(Compass.N, MoveCommand.BACKWARD): self._current_position.y < 10,
(Compass.S, MoveCommand.FORWARD): self._current_position.y < 10,
(Compass.S, MoveCommand.BACKWARD): self._current_position.y > 0,
(Compass.E, MoveCommand.FORWARD): self._current_position.x < 10,
(Compass.E, MoveCommand.BACKWARD): self._current_position.x > 0,
(Compass.W, MoveCommand.FORWARD): self._current_position.x > 0,
(Compass.W, MoveCommand.BACKWARD): self._current_position.x < 10
}[(self.direction, move_command)]
```
usage:
```python
if self.check_boundaries(move_command):
```
It could be hard to understand how it works for those non-pythonist (like myself). I will try to explain it below.
For sake of simplicity I will focused only in one case:

Non-pythonic way:
```python
def check_boundaries(self, move_command):
if self.direction == Compass.N and move_command == MoveCommand.FORWARD:
if self._current_position.y > 0:
return true
else
return flase
```
Pythonic way:
```python
def check_boundaries(self, move_command):
return {
(Compass.N, MoveCommand.FORWARD): self._current_position.y > 0
}
```

4. **Music** to help you out staying in the `zone` [x-team radio](https://radio.x-team.com/)

Expand Down

0 comments on commit 999a33c

Please sign in to comment.