11 ms·
Good and Bad Elixir
- macintux 5y agoNice. Solid advice from Chris. I’d wondered about the pipes construct in Elixir for exactly that reason. Sure, it looks nice and easy, but based on my experience with Erlang it seemed unlikely to be useful unless you are simply planning on crashing for any errors (which isn’t really the Erlang way).
- hmmokidk 5y agoYou can use changesets or a similar pattern to avoid this.
- jkhdigital 5y agoPipes are still plenty useful for chaining simple functions that aren’t going to cause trouble (because you validated the inputs already, or whatever).
- msie 5y agoLots of good points. I gotta blame my Elixir tutorial (Dave Thomas) for some bad habits: over-reliance on pipes and pattern-matching in function args. He hates if-then in a function. He would take an if-then in a function and split both clauses out into their own function. Seemed fishy to me. Trying too hard to be elegant.
- macintux 5y agoI agree with Dave on the pattern matching in function heads, at least from your description. Garrett Smith’s blog post on tiny functions[0] has heavily influence my Erlang. [0]: http://www.gar1t.com/blog/solving-embarrassingly-obvious-problems-in-erlang.html http://www.gar1t.com/blog/solving-embarrassingly-obvious-pro...
- ludamad 5y agoI notice he says the result needs less testing; to me such a rewrite amounts to an audit of the code and thus leaves one with more confidence, definitely. I'd just buy it more perhaps with stringent static types, but I've become a 'gradual typing purist' in a way (in this process, if you're not littering types everywhere you are missing a lot of value)
- nivertech 5y agoThere are lots of contradicting advice in the Erlang/Elixir land. Garret Smith likes microfunctions, while Saša Jurić avoids them. Same with "tagged with statement" pattern - Saša Jurić prefers it over Ecto.Multi in transactions, while this post discourages it's use at all.
- nemetroid 5y agoThe author uses the word "religion" in a jocular manner, which seems appropriate, but probably not in the way he intended. This particular style often seems to get applied as a dogmatic pattern. The underlying principles are good, but the author should have stopped halfway. For example, the article has this: handle_db_create_msg(Msg, State) -> log_operation(db_create, Msg), handle_db_create_result(create_db(create_db_args(Msg)), Msg, State). create_db_args(Msg) -> [create_db_arg(Arg, Msg) || Arg <- [name, user, password, options]]. create_db_arg(name, Msg) -> db_name(Msg); create_db_arg(user, Msg) -> db_user(Msg); create_db_arg(password, Msg) -> db_password(Msg); create_db_arg(options, Msg) -> db_create_options(Msg). create_db(Name, User, Password, Options) -> stax_mysql_controller:create_database(Name, User, Password, Options). There is no shared logic between the different cases in create_db_arg() (creating a false sense of abstraction where there is none). create_db() has to take its arguments as a list* in order for the design to work, but the use of a list suggests homogeneity between the elements, which is not the case. It would have been much better to stop at this point: handle_db_create_msg(Msg, State) -> log_operation(db_create, Msg), Name = db_name(Msg), User = db_user(Msg), Password = db_password(Msg), Options = db_create_options(Msg), Result = stax_mysql_controller:create_database(Name, User, Password, Options), handle_db_create_result(Result, Msg, State). *: which the author also forgot when making the final listing at the end of the blog post.
- derefr 5y agoMind you, when some of the Elixir books were written, the `with` syntax didn't exist yet.
- ConanRus 5y agoThis is a standard Erlang pattern and what's make it so great. And Erlang VM is optimized for that.
- matt_s 5y agoHaving lots of gnarly if-elsif-else blocks of code elsewhere where the logic conditions are varying in number it is nice to encapsulate that in a pattern match function. For me, it doesn't mean "thou shalt not use if-then ever" just that if you have enough conditionals and logic needed, pattern matching is better suited for those cases (sorry for the pun).
- msie 5y agoGood to hear all the opinions. I'm an Elixir newbie and I appreciate them.
- brightball 5y agoI came out of that Dave Thomas classes with a lot more good habits than bad. I don't follow everything he does, but the vast majority of it made a lot of sense to me and results in much cleaner code.
- innocentoldguy 5y agoI started my Elixir journey with Dave Thomas, too, and I agree with your commentary. I think most of Dave Thomas' style is highly organized and readable. One of my favorite Dave Thomas tidbits was writing private functions like this: defp _private_function(params) do # Do something end Whenever I see a function that starts with an underscore, I KNOW it is a private function in the current module. I don't have to go looking for it or wonder where it came from. I know at a glance that it is a private function. Readability and organization are so important in code and I felt that Dave Thomas helped me get off to a great start in this regard.
- ofrzeta 5y agopattern-matching in arguments means that the picking the function according to its signature is the actual decision process? If you have a function that doesn't contain a decision it is easier to unit test, isn't it?
- innocentoldguy 5y agoNo. It's the same. If you have a function with a large if statement in it, you'd want to test all conditions within that if statement to make sure it was working, right? You'd do the exact same thing if you were testing a series of pattern-matched functions. The tests would be unchanged either way.
- jkhdigital 5y agoI think it makes it easier to tick off the list of cases that need to be tested: one for each head.
- ofrzeta 5y agoYou'd have the number of tests broadly but they are simpler because they don't need to handle the cases hidden in the functions themselves. Maybe in the end it's the same or a matter of taste but it recently occurred to me that unit testing becomes "cleaner" that way.
- whalesalad 5y agoI am in love with Elixir but am still on like a 1 out of 10 on the mastery scale. Love seeing posts like this! (I bit off more than I can chew by trying to write a full-featured API for an embedded GPS device that speaks a proprietary binary protocol - it's been a slow project)
- jolux 5y agoI disagree about not using the module-specific `get` functions. They should be used when you expect what you’re operating on to be a specific type. Sometimes I want to write a function that only operates on maps, and Map.get will throw an error if you pass anything else. Granted, I write specs for all my functions, and I come from a static language background, so this is just my perspective. Other than this quibble I think this is solid advice.
- keathley 5y agoInterestingly enough, my advice to not use `Map.get` is the most contentious point in the entire post. I didn't suspect that would be the case. I'm certainly not against using those functions and the additional checking can be of use in certain circumstances. The use case I had in mind was specifically how people will use `Keyword.get` to grab configuration values or options. This means that if you load configuration from a json file or external service, and it comes back as a map, you now need to convert to a keyword list just to initialize a library. Its a small thing, but in those situations I would rather allow for more flexibility in the interface. That said, I think this advice is particularly useful for people building libraries more so then people working on applications. I may try to add more nuance to this point in the post.
- jolux 5y ago> The use case I had in mind was specifically how people will use `Keyword.get` to grab configuration values or options. It seems like this advice is very dependent. I think you should decide whether a function accepts maps or keyword lists or both, but I do not think that all functions which operate on key-value structures should default to accepting both. They have very different performance characteristics, and keys are not unique in keyword lists.
- keathley 5y agoI agree on the performance characteristics. But if your using `get` then it doesn't matter that keyword lists have non-unique keys. You just get the first one.
- toolz 5y agoAgree with almost everything, but one point doesnt attempt to reason about the pattern. Why shouldn't I pipe into a case expression? It's visually pleasing, more concise and removes an empty line. Easier to talk about where I disagree, but overall great read!
- plainOldText 5y agoYeah, it wasn’t obvious why one should avoid |> case. I also think it looks pleasing, plus it’s easy to read and it avoids allocating a new variable compared to the alternative example given.
- keathley 5y agoI didn't make a very strong case for it. Overall, my experience has been that calling the side-effecting function in the case statement directly tends to be easier to maintain and easier to read. But, I think piping into case can work well in certain situations. Its not one of the points that I feel that strongly about.
- skrebbel 5y agoI love this article to bits. The elixir community loves blogging, but so much elixir content is absolute beginner stuff, and so much of the remainder is unopinionated, descriptive stuff. I've found it really hard to strike on some good "how to best do xyz, what are the tradeoffs" style knowledge. This article is the first elixir thing I've read in a long time that really made me go "o wow yeah, I've been doing that wrong". Cool stuff!
- keathley 5y agoThanks! I'm glad you enjoyed the article and it could provide some useful insights.
- SinParadise 5y agoI think this is true for most programming languages. I want more stylistic, opinionated stuff that comes with contexts and caveats, so I can get to understand their decision making process and avoid footguns that can only be learned through sufficient experience.
- mikepurvis 5y agoI totally agree, though I think those articles are a lot harder (eg requiring more skill) to write well because you need to quickly ramp your readers on all of whatever the context is that's necessary to actually appreciate the nuance of the design decisions under discussion. You're basically by definition going to be out of the realm of "just follow best practice X" or "apply pattern Y or you're doing it wrong." As a small example, I've been working on a small asyncio-based web service (Python) which is oriented around an expensive process that generates a result, where the result is stashed in sqlite and returned. I knew upfront that I needed a way to track when a particular result was already being prepared so that if I got a second request for it, it would collapse it into the first one and only do the work once. I wrote this as a twenty line memoizing decorator, but it turns out this issue as a name— cache stampeding. Once I realized that, I discovered that there are existing (and much more complicated/tunable) solutions to this problem, such as https://github.com/DreamLab/memoize/ https://github.com/DreamLab/memoize/, but the article pitching that solution spends quite a bit of time getting to it— enough so that if I'd discovered it before building my own, I'm not sure I would even have appreciated its applicability: https://tech.ringieraxelspringer.com/blog/open-source/caching-in-the-world-of-concurrent-python-harder-than-ever/8nq1c41 https://tech.ringieraxelspringer.com/blog/open-source/cachin...
- losvedir 5y agoGood stuff. I disagree about the first point, though, and have actually gone the opposite way, going from generic Access via `[]` to specific `Map.get` and `Keyword.get`. The reason is that the underlying data structures are quite different, and operations and access patterns on them shouldn't be agnostic. You should use Keywords basically only as options to functions, in my opinion, and that's just for historical consistency and interop with Erlang. Otherwise key-value pairs should be a map. And using `Keyword.get` and `Map.get` make it immediately obvious what the underlying data structure is, as well as prompt you to think about whether you should use the `!` version or provide defaults. Otherwise, I think the tips are all decent to great. I am a little on the fence with exceptions, though. I know there's a meme in the community of "let it crash", but in my experience, that rarely feels like the right thing to do. I much prefer a Rust-style, "Result-all-the-things". It seems hard, in practice, to rely on crashes and restarts to maintain the right state invariants.
- dnautics 5y ago> It seems hard, in practice, to rely on crashes and restarts to maintain the right state invariants. I feel the opposite way. Perhaps if you are mostly doing things where you have control over a transient state (like a chain of validations on a database entry) the error tuples are easy... But if you are doing something like checking in on cached state for something remote that you don't have control over... It is so, so much better to give up, restart your GenServer, and re-sync your cached state in the init() clause than try to "guess" what the remote thing has for its state after it's sent back an error.
- losvedir 5y agoI dunno, I rarely get issues that crash just once. For example, in the blog post, it's recommended to use `Jason.decode!`. But what if whatever server you're hitting is returning invalid JSON for a time? If you crash, the GenServer will restart, it will crash again, and it will just be either in a crash loop (meanwhile DOS-ing the server?), or worse - if it happens in `init` - will take down its own supervisor after a number of failures, cascading up the tree until your app crashes and restarts. I think it's better to handle the Jason.decode error, and apply some sort of backoff strategy on re-requests. In general, you have so little control over the timing and count and rate of restarts. It's a very blunt object to just crash. Again, with the `Jason.decode!` error, suppose it's in a GenServer that's updating its state. In some cases you may want to reset the state to empty (essentially what crashing does) and in other situations you may want to keep the previous state, from the last time you made that request. Maybe you want to track how many consecutive failures you're seeing and maintain the state for some time, but eventually blank it, or crash at that point. It could very well depend on the problem domain, though, for sure. I mostly work on freestanding, pure Elixir apps, and a couple of Phoenix apps. I'm more thinking about the freestanding apps, since in Phoenix, sure, just crash your request, whatever.
- brightball 5y agoWe had a good discussion on this article yesterday in my local Elixir group. General consensus is that there's a lot of things pointed out here that are good to think about and consider, but don't treat them all as gospel. Some situations are better handled by other approaches, but understanding the goals of why the author has pointed these out will be beneficial for everyone.
- keathley 5y ago> General consensus is that there's a lot of things pointed out here that are good to think about and consider, but don't treat them all as gospel. Definitely not gospel. These are patterns that I tend to use and believe have helped increase the maintenance of the various projects I've worked on. But I'm also guilty of going against these points when it seems appropriate.
- aeturnum 5y agoI disagree with so much of this! Though I can tell the author is coming from a lot of experience. How often is it that you don't know if you're expecting a map or a keyword list? I don't think I've ever intentionally put myself in that situation (though it's nice that access supports both). They say to avoid piping result tuples, but I actually think their example code shows the strength and weaknesses of both approaches. I use pattern matching on tuples when you want more complicated behavior (that might be hard to read in a big else block for a with) and a nice with statement when there's 'one true path.' In general, I think one of my favorite things about Elixir is that they've done a good job of avoiding adding features you should never use. These all feel like personal judgements about tradeoffs rather than actual hard rules.
- mattbaker 5y agoYeah, I disagreed with a decent amount, but I tried to read it as “here are the patterns and practices I feel passionate about” and that made it an interesting read for me. The sort of declarative good/bad language worries me a bit because people new to the language may take it as gospel, but overall I’m glad to see people putting their thoughts out there with explanations and examples :)
- aeturnum 5y agoI do think that being opinionated about code style leads to code that's easier to read and maintain. I was just delighted to find someone whose tastes diverged so distinctly from my own in a smaller language community.
- bcrosby95 5y agoAside from using an automated formatter/linter, I think being opinionated about code style is only really sustainable for single person projects. Otherwise it leads to inconsistent code reviews where people are making changes for reasons they can't understand.
- innocentoldguy 5y ago
- mattbaker 5y agoI think a lot of this is subjective and context dependent so the definitive “this is good” and “this is bad” language was a bit of a turnoff. BUT, I did like seeing someone’s point of view with thoughtful explanations and examples, kind of like what you get out of a good discussion at an elixir meetup or something :D I enjoyed reading it.
- keathley 5y agoCalling it "good and bad elixir" was probably overly charged. Its a little late to change it now, but something I'll consider in the future.
- acrispino 5y agoI don't see how it's too late, unless HN commenters from today will be the only audience. You could also add an note.
- hdra 5y agofwiw I enjoyed the article, i agreed with some of them, disagreed with the others, but overall I liked the perspectives presented in the article... can you elaborate more on the "Don’t pipe into case statements" point though? Not entirely what you're saying with this one as there isn't any explanation why one might be better/worse than the other, other than aesthetic/personal preference. Needing to access the result from the previous pipe in the case maybe?
- dnautics 5y agodon't feel too bad about it: It would probably have gotten fewer eyes if you had named it more mildly.
- rubyn00bie 5y agoA lot of a great advice! but I'd like to shave some yak on my lunch so I'll comment on what I disagree with :) I sort of disagree with Access vs Matching vs Map; if I change my data structure I'm changing the contract I've established. I want things to break in that case, and I want them to break as fast as possible. This seems like great advice for a controller action, not so much for a gen_server or anywhere I'm NOT dealing with user input. And... I completely disagree with "Raise exceptions if you receive invalid data." If you receive invalid data return an error saying that... please for the love of someone's god, do not raise an exception. You have no idea what the concerns of the caller are, so just return an error tuple. > This allows us to crash the process (which is good) and removes the useless error handling logic from the function. No, the exception returned will likely have no meaning to the client and will more than likely confuse them or your. You will still have to write error handling logic. You still have to format the error. You still have to log or report the error... Now you are doing it in multiple places because you're raising and likely still having to handle data validation issues. The best of both worlds, IMHO, is returning an `{:error, exception}` tuple. Edit: Forgot the "NOT" in the end of the second paragraph.
- etxm 5y agoSo much this. “Let it crash” is cargo culted too hard IMO. If a caller (being another library or end user) can be given information to correct an error, give it! Let it crash works well for a phone system where it doesn’t make sense to call both parties back if the thing failed.
- querulous 5y agolet it crash is great for unrecoverable errors as it gives you clean state as if the thing that caused the error never happened but it's terrible for cases where you want to actually capture the error and react to it. give me a structured log event or an error code every time over a stack trace
- dnautics 5y agoUh I think the rule of thumb is, if you're writing a library do return an error tuple because it gives the caller the option, and if you're a mensch also provide a bang function. If you are consuming a library in most cases let it crash.
- hmmokidk 5y agoThis captures exactly how I feel about with. Really good article.
- phtrivier 5y agoThe part about 'with' and 'else' is interesting but slightly conractictory with the part about handling errors in the "higher" function. That being said, my main issue with nested 'with' (or nested 'case', for that matter), is that nothing helps you make sure you handled all the possible way for any of the nested function to fail. And someone, someday, is going to add another way for one of the functions to fail, and you will not have written a handler for that because you're not clairvoyant. And you won't notice until it crashes in prod, and your customer complains. Good advice overall, otherwise !
- supernintendo 5y agoI agree with almost all of this except for avoiding else and annotation in with statements. Here’s my reasoning: 1. The argument the author makes here assumes that else clauses can or should only used be for error handling. There are instances where you might want to drop out of a with statement without returning an error however. Some examples might include connection Plugs that don’t need to perform some behavior due to certain assigns already being present on the Connection struct or configurable / optional behavior encoded in an options list. In these instances, pattern matching on a successful fallback clause actually reduces complexity as it avoids the need to position that branching logic somewhere outside of the main with statement that it is actually concerned with. 2. I find error handling through with / else and annotated tuples to actually lead to very expressive, easy to read code. Having built and maintained a Phoenix application in production since 2015, this is actually a very common pattern I and other members of my team use so I’m curious as to why the author considers it something you do under “no circumstances”.
- david_allison 5y ago(non-Elixir dev here) Does Elixir have anything akin to Haskell's "do notation" for result types? The provided best practice code feels verbose, and that surprises me given that Elixir looked clean & modern. For example # Do... def main do with {:ok, response} <- call_service(data), {:ok, decoded} <- parse_response(response) do decoded end end would read in C# (.NET 3.5) as the following pseudocode, which personally looks much cleaner, avoiding `{:ok, ...}`: Result<T> Main(object data) { return from response in call_service(data) from decoded in parse_response(response) select decoded; }
- jolux 5y agoKinda, see https://hexdocs.pm/elixir/1.12/Kernel.SpecialForms.html#with/1 https://hexdocs.pm/elixir/1.12/Kernel.SpecialForms.html#with...
- Grimm1 5y ago{:ok, foo} is just the largely community adopted soft error pattern in elixir call_service could just return response and remove the verboseness. so it would be: response <- call_service(data) I don't know C# but would that code explode if there was an error, instead of in again the soft error pattern likely getting {:error, foo} ? Regardless my point is that {:ok, bar} stuff isn't a language required aspect it's a community pattern if that makes it any better for you.
- masklinn 5y ago> {:ok, foo} is just the largely community adopted soft error pattern in elixir It is not a community pattern, because it's the way OPT (Erlang's "standard library") functions work e.g. maps:find? returns `{ok, Value} | error`. And Elixir inherited that rather directly and build its standard library the same way. `Map.fetch` similarly returns `{:ok, value()} | :error`. It's not hard-coded into either language, but it's absolutely not "community adopted" or "a community pattern" either.
- Grimm1 5y ago
- devoutsalsa 5y agoI don't really like this article cuz: - I like &Map.get/3 over the some_map[:some_key] syntax - &with/1 can be hellza confusing in many case if you're calling a bunch of functions, and any ol' one of them can return an error message (e.g. where the heck did `{:error, :bad_arg}` come from?! - piping into case statements is awesome, and I'll only stop doing it when people complain about it - higher order functions are useful, and I don't see a problem using one's judgement as need on when to use them - In the cases where using &with/1 is actually useful, so is using the else block if you really need to ... Yeah, I just don't like this article's recommendations.
- cormacrelf 5y agoI’ve never used Elixir, but when I saw piping into case statements I was confused as to why it’s appearing on a ‘do not use’ list. It does seem awesome! The key thing for error handling is to be able to do it inline, without introducing nesting, like those withs are doing. Maybe you don’t get that with case either. Does elixir have a return statement?
- pipingdog 5y agoElixir does not have a return keyword.
- jkhdigital 5y agoElixir, like Erlang, is functional so there are no statements. Everything is an expression, which evaluates to some value when executed. The “return” value is just the value of the last expression evaluated in the function call.
- cormacrelf 5y agoIs there an equivalent of the Haskell Either monad & do-notation / Rust Result + the ? (try) operator?
- mcintyre1994 5y ago
- Grimm1 5y agoAgree with many things, big disagree with not using 'else' with 'with' and actually for the same reason you stated not to use it. I use 'with' when I have a pipeline, but the error conditions in the pipeline matter. In fact the example you gave in the article is exactly one of the cases where I think 'with' and 'else' are useful because you can clearly show the dependency of each action in the pipeline and clear failure cases to address them. I think there is a limit to how many things you should handle in a with statement, but the same goes for regular pipes as well.
- keathley 5y agoMy general feeling is that if the errors matter, `with` probably isn't the right construct. In those situations I prefer to use case. That's been helpful in my experience.
- devoutsalsa 5y agoIf the errors don't matter & there's no real chance of returning an error, why use &with/1 at all? &with/1 has the quirky behavior in that the return value of anything that doesn't pattern match get returned. So if &call_service/1 or &parse_response/1 doesn't return an an ok tuple, you're increasing your debugging surface by having to track down where the unexpected result came from. Good luck tracking down that rogue nil! Instead of this... with {:ok, response} <- call_service(data), {:ok, decoded} <- parse_response(response) do decoded end Maybe just do this... {:ok, response} = call_service(data) {:ok, decoded} = parse_response(response) decoded Or even this... data |> call_service!() # don't bother returning ok tuples |> parse_response!() # just use bang methods!
- jib_flow 5y agoI feel like the number of "I agree with everything except..." posts on this thread is an indication of what a great article this is. Practical, real world, and takes enough of a stand to wake up the pedants.
- pselbert 5y agoOne of the best parts of listening to Elixir Outlaws, the podcast that Chris co-hosts, is disagreeing with his wacky and strongly-held opinions on things. Personally, I don't agree with most of what he's calling out here, but it's still a great read to get you thinking.
- 1_player 5y ago> Don’t pipe results into the following function Mmmm. No. It makes sense into context of the example, but this is way too generic advice it's actually bad. Pipes are awesome. Please _do_ pipe results into the following function when it makes sense to.
- janderland 5y agoI didn’t get the impression they were saying never to do it (maybe I missed that bit in the text). I think they specifically said, when piping, don’t force functions to handle the error of the upstream function. Because each error needs to be handled differently, the downstream function’s implementation becomes tied to the upstream function. Then the downstream function is only usable with said upstream function.
- devoutsalsa 5y agoThe more I need to handle errors, the more I want to make every unexpected thing just raise an exception. 500s for everyone!
- jkhdigital 5y agoExactly, piping a bunch of ! functions is the way.
- conradfr 5y agoI never thought about piping into case ... I guess I'll try it next time ;)
- devoutsalsa 5y agoIf you really wanna piss OP off, pipe into &if/1 :) iex(2)> :something |> if do true else false end true iex(3)> nil |> if do true else false end false
- princevegeta89 5y agoA few more thoughts from my 2c coming based on my experience writing a lot of code in Elixir: 1 - avoid if else {} blocks, use `cond do .. end` blocks instead, they're more readable 2 - avoid importing modules, but rather use them directly wherever possible, this will help when refactoring code or to find all occurrences of a particular Module.method() 3 - when specifying keyword list options, explicitly supply [ ] in the arguments, example: Abc.method(a: 2, b: 3) may be clearly written as Abc.method([a: 2, b: 3]) so we always know it uses a keyword list and not map 4 - Use a file `.iex.exs` to specify all your aliases and macros you may need in your Elixir shell. Helps a lot while you're playgrounding in the IEx shell. In my case, I have aliased all my Context modules and Model modules 5 - Pattern match everywhere. This is one of the powers of this language. Make your methods follow the {:ok, data} or {:error, message} pattern and it's already very maintainable.
- devoutsalsa 5y agoI've been using Elixir for over 5 years and didn't know about .iex.exs. Nice!
- innocentoldguy 5y agoHere's a handy thing you can do with .iex.exs: Have you ever tried to debug something in iex, but database calls and other log messages keep stomping all over your prompt? You can stop them temporarily calling the function Logger.remove_backend(:console) You can start the log message again by typing Logger.add_backend(:console) That's a lot of typing though. Here's where .iex.exs comes in handy. You can include the following code in your .iex.exs file: defmodule Clog do def stop do Logger.remove_backend(:console) end def start do Logger.add_backend(:console) end end and then from within your iex session, type Clog.stop to stop the log message flow and Clog.start to start it up again. You can call your module whatever you'd like. I just called mine "Clog" because the log messages were always clogging up my console. I hope this helps.
- dnautics 5y ago
- 71a54xd 5y agoI write elixir full-time at a fintech startup and I can confidently say that this blog is clearly written by someone with significant experience. With statements are key to nailing a balance of error handling and pattern matching, however for trivial functional flows (that don't require error handling), pipes are entirely fine. The biggest challenges for elixir currently are the lack of established HTTP libs with dynamic testing and db ORMs. For instance, interacting with PSQL is fine using ecto, but using a document based DB or something like Neo4J is an absolute headache. Deployment is also pretty easy, but that's a whole different side of development.
- sergiomattei 5y agoI'm so glad to hear that last bit: seems like the deployment story in Elixir has really improved lately. It wasn't long ago where the only posts in here would describe it as the biggest headache!
- abanayev 5y agoNot related to Elixir, but I disagree with the last point: you should not have test assertions inside loops at all, because it makes a test less readable and the diagnosis harder when a test fails. You shouldn’t have to unpack complexity just to understand where a test failed or whether it failed because of bad test code or bad tested code. Once you have so much complexity that reading and mentally executing the test takes time, you should probably be writing tests of your unit tests.
- travisjungroth 5y agoIn Elixir would it also mean that all assertions after the first failure don't get ran? Cause that's how it works in most other languages. The better (but maybe slower) alternative is parameterization.
- innocentoldguy 5y agoLike many others, I disagree with more of these points than I agree with. I DO agree that you shouldn't wrap Enum functions inside of other functions, but I prefer using Map.get(foo, :bar, :some_default_value) over foo[:bar] because I dislike dealing with meaningless nil values, since they tend to be the source of bugs. I also disagree with not using else in a with statement. That advise seems a lot like, "Next, pull out your pistol and shoot yourself in the foot," to me. Languages have idioms for a reason and a lot of these suggestions go against idiomatic Elixir, which I'd recommend against.
- devoutsalsa 5y agoIn cases where something really should be in the map, I like to use &Map.fetch!/2.
- nivertech 5y agoThis will work with both maps and keywords: iex(1)> foo = %{a: 1, b: "test"} %{a: 1, b: "test"} iex(2)> foo[:bar] || :some_default_value :some_default_value iex(3)> foo = [a: 1, b: "test"] [a: 1, b: "test"] iex(4)> foo[:bar] || :some_default_value :some_default_value This looks like some Perl-ism/Ruby-ism. I personally dislike truth-y/false-y values, as they do more harm than good, and making it harder for dialyzer to infer boolean types. Also Map.get/3 and Keyword.get/3 are probably faster.
- kvnhn 5y ago"Don’t hide higher-order functions Higher-order functions are great, so try not to hide them away. If you’re working with collections, you should prefer to write functions that operate on a single entity rather than the collection itself." Excellent advice -- and not just for Elixir. I find myself applying this technique often in Python, for example. While the example is fairly simple and contrived, the consequences they note ring true.
- devoutsalsa 5y agoYeah, I misread the bit about about higher order functions (or they edited the article).
- allanmacgregor 5y agoFor the example that the OP listed in regards to pipes I prefer to leverage something like https://github.com/CrowdHailer/OK https://github.com/CrowdHailer/OK it allows to retain the expressiveness you get with pipes but cleanly handles result tuples: require OK OK.for do user <- fetch_user(1) # `<-` operator means func returns {:ok, user} cart <- fetch_cart(1) # `<-` again, {:ok, cart} order = checkout(cart, user) # `=` allows pattern matching on non-tagged funcs saved_order <- save_order(order) after saved_order # Value will be wrapped if not already a result tuple end
- jFriedensreich 5y agoI have similar feelings to others here but not necessarily disagree with most points, my problem is more that the author does not really explain enough why his rules are true. Even if some problems he states are understandable i would expect to also give examples why other alternatives are bad...