I came across the Protocol-Oriented programming concept recently and I found it quite fascinating, so I decided to rewrite my previous story with protocols and value-based approaches.
The first thing I need to do is layout all the requirements:
- I want to model all the creatures in the world including animals and plants.
- Basically all creatures have names. The difference between animals and plants is whether they can move, generally speaking.
- All the moving animals have their own ‘Escape Strategy’. But how do they execute their strategies varies.
The next step is to write some concrete struct / class to actually conform to the protocols. The power of protocol inheritance and composition makes it quite easy and flexible to do so.
Finally test the code: