Clojure Protocols

So if you remember my last posts:



I mentioned closure protocols as an option for the design problems i was talking bout but i didn't not show any code or explain much around it. So this is basically one another approach for you to design your software. 
Show me the code!


The principle here is simple, its very similar to classes and interfaces in OO. A *defrecord* its a definition of a structure or type, so this it`s like a class in clojure. a Protocol you do by *defprotocol* its a definition of a trait/interface so you have a name and a list of function that the protocol support.

So we start defining a tax-service protocol that have a function called toll-one-way. With that we can defined 2 records(structures) that behave totally different but with the same data. So brazillian one will charge 6.95D and Argentinian one will charge 16.95D.

A cool thing clojure can do its categories/extension of current data structures and functions so we are adding the toll-one-way to string structures on line 12-14. Doing a function delegation to brazilian-service record/protocol.

So as you can see on lines 16, 18 and 19, we can do both string creation of the protocol with extended-string protocols or explicit use brazilian argentinian structures. In principle this is not that different form the first solution i pointed out on the first post. 

The advantage here is that the code size is very small, so we do way more with less code.

Cheers,

Popular posts from this blog

Telemetry and Microservices part2

Installing and Running ntop 2 on Amazon Linux OS

Fun with Apache Kafka