Skip to content

Instantly share code, notes, and snippets.

@KnowledgeGarden
Created November 26, 2021 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KnowledgeGarden/2dc4d57ac59ba856584fb59f206e957e to your computer and use it in GitHub Desktop.
Save KnowledgeGarden/2dc4d57ac59ba856584fb59f206e957e to your computer and use it in GitHub Desktop.
protocol-record test
file: backside_api.clj
(ns stm4clj.backside_api)
(defprotocol IBackside
(put-proxy [proxy]) ;; wavering on whether "this" is needed
(get-proxy [locator])
(delete-proxy [locator])
(find-proxy [query])
(list-proxies [offset count])
)
file DhPgBackside.clj
(ns stm4clj.DhPgBackside
(:require ;; [stm4clj.types :as t]
;; [datahike.api :as d]
;; [stm4clj.postgres :as pg]
[stm4clj.backside_api :as api]))
;;;;;;;;;;;
;; This is an IBackside implementation which
;; drives Datahike which is persisting with Postgres
;; @see https://www.juxt.pro/blog/abstract-clojure#_protocols
;;;;;;;;;;;
;;(defn boot-db
;; "boot the database
;; Intended to eventually validate there is a database and
;; otherwise configure one if not"
;; []
;; (pg/create-db)
;; (println "Booted"))
(defrecord DhPgBackside []
api/IBackside
(put-proxy [this proxy] ;; wavering of whether "this" is needed
(println "Put" proxy) ;; for testing
nil)
(get-proxy [locator]
nil)
(delete-proxy [locator]
nil)
(find-proxy [query]
nil)
(list-proxies [offset count]
nil)
)
file: core.clj This is where it's problematic how to require/import the implementation and use it
(ns stm4clj.core
(:require
[stm4clj.DhPgBackside])
(:gen-class))
(defn foo
[]
(DhPgBackside/put-proxy "foo")
(println "Hello, World!"))
@lukaszkorecki
Copy link

lukaszkorecki commented Nov 27, 2021

(require '[stm4clj.DhPgBackside :as bc]
      '[stm4clj.backside_api :as api]
)

(let [pg (bc/->DhPgBackside)]
  (api/put-proxy pg "foo"))

@KnowledgeGarden
Copy link
Author

That made it work just fine. Many thanks!

@lukaszkorecki
Copy link

@KnowledgeGarden happy to help! Protocols and records are somewhat confusing as there's a bit of magic going on under the hood (particularly around how protocols are turned into interfaces and automatic creation of factory functions for records), but once you grok it, it all works quite nicely together - just don't over do it - idiomatic Clojure code mostly operates on data rather than concrete types/classes etc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment