DEV Community


Discussion on: How to Utilize Enum.any?, with a Refactoring Twist!

wulymammoth profile image
David • Edited

Nice post, Noel!

I, too, have seen Elixir code that's gone awry with a bunch of nested conditions. It's usually a code smell whether we're operating in a functional programming or not.

Enum.any? def looks like it helps in flattening. Another thing that I've found useful, and maybe you will as well is with special form. I rely it on quite a bit when the pipe operator is not applicable, because the functions all return an ok/error-tuple (i.e. {:ok, _} / {:error, _}) or don't handle them. I love Drew Olsen's post on the topic here

And lastly, I think you spotted what part of the issue was -- ensuring that the data-types match. Dealing with numbers and money can be hairy business. I've used the the money library in the past and actually just included in a new project that I started - I typically also perform all data clean-up in the controller before they ever enter any business domain code (which also includes validations). I ensure that maps are converted to structs (never handling data that isn't well-formed and no maps with string keys unless its metadata), decimals that are supposed to represent money to currency structs (via the money library) all before pushing them through changeset validations. I'll let the consumer/client know that their request is malformed and return 4xx if it isn't structured correctly. By the time it reaches the changeset validations, the datatypes should be correct and I can run validations without performing data-type transformation from one type to another just to compare them. I'm free to just just validate whether the values are valid or not.

noelworden profile image
Noel Worden Author

Hey David,

Thanks for pointing me to the with expression. I actually wrote a post of my own here. I am by no means an expert, but just writing the post helped me get a better handle on all the possibilities.

A big caveat we have in the project I'm working on is when/if to do the rounding. I ended up rolling my own module to simply add the $ and commas in the correct positions, since ultimately that's all we needed.

Thanks for reaching out, I appreciate the feedback and advice!

wulymammoth profile image

Ah! Totally missed that! Hard to go back to Ruby after all this jazz, huh?