mmport80
Let's talk about Guards
To those who consider themselves heavy users of guards, could you share your rules of thumb?
When do you or don’t you use guards?
How about errors resulting from guards?
How do you think about them for different types of functions?
First Post!
NobbZ
My rule of thumb is to use them when I need them. Or what do you mean?
And what do you mean by “errors from guards”? If something raises in a guard, it is considered as if the whole guard is false.
Most Liked
dimitarvp
It is tedious alright. But I still try my best to use guards and limit what I receive even in my private functions.
Since Elixir is not statically typed and never will be – and since I want to use Elixir almost everywhere in my work – I compensate with guards and pattern-matching so as to catch errors as early as possible. Never again will I just catch the root of all exceptions (like many Java devs do) and just turn a blind eye to weak spots in the code.
BTW don’t forget about the relatively new defguard construct. It made my stricter code look cleaner.
StefanHoutzager
You can use them as a complement to a patternmatch (edit: qqwy already named that, example:)
defp get_task(%{:type => a} = element, socket) when a in ["exclusiveGateway","parallelGateway"],
do: get_tasks_after_element(element.id, socket)
Qqwy
I use guards in two cases:
- To help with pattern-matching when I have multiple functions. Usually these functions are then ‘complete’ (as opposed to ‘partial’ functions).
- To constrain the input types of the functions, especially when they are part of the public API of whatever it is I am writing.
Last Post!
dimitarvp
Absolutely. You are basically coding against a contract afterwards which makes things much clearer and more productive.
Yep. If we didn’t have that we might as well just code in vanilla Javascript. To me guards and pattern matching are a core value proposition of Elixir.
Popular in Discussions
Other popular topics
Chat & Discussions>Discussions
Latest on Elixir Forum
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









