#Motivation behind passing Ecto struct into function instead of passing id

6 messages · Page 1 of 1 (latest)

novel vault
#

I have noticed that there is a convention that when creating functions (Especially ecto related ones) the first argument is a struct. I was wondering why is this the case instead of just passing in the id?

I understand that if you already have the item loaded it makes sense but I find myself usually needing to call Items.get(id) first before something like Items.update(item_struct, params).

This happens especially why I try and use iex for local testing.

leaden herald
#

In general, it’s a good idea to realize data at the edges of your application and pass the data structures around rather than find them again and again inside your app. Having functions that take ids will invariably lead to performance issues.

#

Additionally, ids are very often just numbers, and convey nothing to uses of your code (like what thing they reference), while structs tell users of a function exactly what it expects.

novel vault
#

Thank you that helps a ton. Is there any way to simply using your core modules while in iex? Essentially if I want to use the core functions for a context that use the structs, is there a way workaround to avoid always finding the struct by id first? It adds a little bit of friction to just testing things quickly

iex> todo = Todos.get(id)
iex> Todos.update(todo, params)
leaden herald
#

Or, make a module that operates at a higher level than your schemas