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?
Most Liked Responses
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.
Popular in Discussions
Other popular topics
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
- #javascript
- #podcasts
- #code-sync
- #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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








