Help understanding protocols and behaviours

Imagine you have a baking machine, which can bake cookies. That machine allows you to provide a custom sprinkle application system as well as a custom system for cutting out the cookies into their final shape.

A behaviour would be used to document that the module you provide to the baking machine has a function (callback) for running the sprinkle application as needed, as well as the cookie cutting as needed.

You cannot check if a module actually implements a module. The baking machine would just try to initialize e.g. the sprinkle application and fail if it’s missing. Often this is called ducktyping.

Now imagine an oven. An oven can bake many things, but those things all need to be properly prepared for baking. Muffin dough need to go in the muffin tray, a cake dough in a cake ring and the stew in a firesafe pot.

A protocol allows the baking logic to define “If something needs to get baked it needs to provide proper preparation instructions”. Then implementations for muffin, cake and stew can implement that protocol, so baking works without the baking logic needing to know how things are prepared in advance.

Protocol implementations can be checked when protocols were consolidated, but I’d argue you usually don’t want to do so as well.

Both are used for polymorphic code execution, but behaviours are around outer code receiving an implementation explicitly. Protocols are about polymorphism based on the type of data at hand.

6 Likes