Interdependency amongst Contexts

How independent should contexts be?
A more particular question: say I’m writing a blog and I want to make sure no posts are persisted in the database without a user tied to it. Where exactly do I make this check to make sure that always happen?

I’m currently doing this kind of checks in the context functions, and now that I’m increasing the number of contexts in my application I find myself importing a lot of the application just to write context tests, which gives me the feeling that I’m doing it wrong and that there might be a better way to do it.

Any tips on that one?
Thanks :slight_smile:

As a general introduction, contexts are used to expose a public API while hiding the implementation details that aren’t necessary.

That said, it’s common to call some functions from another context while being into one, how or when to do this depends by what you’re doing, hence your domain.

You can also use a dedicated context to glue other ones into a single place and expose inly the functionalities at an higher level. Again, how or when you do this depends by your domain.

When testing a context, you could mock functions from the external contexts.

Hope this helps a bit to clarify :wink:

Edit, more details: regarding your question, if you have Accounts and Blog contexts, and you want Post to have an existing user, at least you can check that user_id is present. If you want a stricter check you can either 1) do a manual check by querying Accounts for the given user_id and see if it exists, or 2) create a database constraint (which breaks some isolation under the hood), or 3) replicate user data on Blog context (a bit overkill in this specific use case).

1 Like

I believe that in many cases, as long as you are able to draw out your dependencies as a directed acyclic graph (in other words: there are no cycles, no contexts that both depend on each-other), then you are usually fine.

1 Like

I think my main issue is seeing how the chain of the dependencies can grow big and make test really weird sometimes.

In this same example, say I created a check to verify that a user is always present in a blog post, but then user itself has its own associations it depends on. There already would have me bringing two other contexts to this just for testing!

Very much this. Your context are unlikely all on the same level of abstraction, but you should always only depend on something of a lower level of abstraction. On recent elixir versions I’d try to get Boundary setup, which can help with such things and also bring more visibility in the otherwise hidden-in-implementation-details tree of dependencies.


Ohh, that looks neat…!