341 points · by muhic · 7y ago · 178 comments
IMO it really does feel like you get the best of everything (developer productivity, developer happiness, great language for creating maintainable code, OTP and the BEAM bring a lot to the table, it's memory efficient, tracing code without a ton of experience is very doable, it's fast as balls and Phoenix channels / LiveView is a great abstraction on websockets). I find myself fist pumping all over the place as I make progress towards this app while learning as I go.
I don't think I've liked a technology this much ever and I'm honestly surprised it's not already more popular than it already is. I've been around for the release of a lot of major frameworks and technologies (Rails / Django, Node, Go, etc.). Nothing has impressed me this much. It truly feels like it's a zero compromise environment to write code in and I hope I can still be using it in 10+ years.
While there is a superficial syntactical difference I think the most important differentiation is the runtimes, the JVM versus the BEAM. JVM will outperform BEAM with regards to computations, while the BEAM has better support for true immutability and concurrency.
With regards to web development specifically the Elixir community seems to more or less have converged around a framework approach with Phoenix, while Clojure (too me) seems more geared towards a collection of libraries approach, á la Node.js.
I don't have much experience with Clojure's tooling story, but the tools that come come bundled with Elixir, like Mix (build tool) and ExUnit (testing framework), are very good. Compared to the languages I have experience with (Python, Ruby, JS, Java, C#) Elixir provides the best developer ergonomics out of the box.
Wanted to thank you again for making these videos, I learned a ton and I'm really into Elixir now. If only there was a way to use it at work!
One of my favorite things about Elixir is Erlang/OTP. It's as if you're in Disneyland and everything's nice and colorful. But sometimes you go into a basement and you discover the entire thing is built on top of ancient Jedi ruins and these immortal, powerful forces lurk just beneath the surface, at your disposal.
Clojure is the opposite. It's all nice and fine as long as you're in Clojureland, but then you look behind the curtain and it's a huge pile of cards and matchsticks that hold everything together, and the glue is made of mutable state and classes.
And man, the tooling. I can't say this enough. It took me about 3 seconds to create a new project with mix new to get the unit tests and everything set up for the flatten challenge. I don't even know how to set up unit tests in Clojure, and I've been playing with it for 5 years.
So basically OTP == "ancient Jedi ruins" :D
It provides a more robust, performant and observable platform for Web development. (Technically JVM is faster batch operations but for Web, most Elixir apps win)
More importantly, it's a perfect fit for immutable functional languages. Everything is immutable and proper tail-recursion are provided. Clojure is great but it has several different ways to define state and type, and sometimes I found they're a little bit awkward. With BEAM process, there's no need for language to have constructs for state/reference/async handling, which could makes the language itself more simpler and more compact.
I would any day prefer Clojure and framework Pedestal.
I think a big part of it has been a lack of learning resources. A major part of why I started my site and YT channel was the frustration I had learning Elixir in 2016. Phoenix was even tougher. At that time, even the paid resources were mostly out of date. I found about 70% of everything I came across (books, videos, blog posts) wouldn't compile on Elixir version > 1.0! The changes in Phoenix 1.2 and 1.3 were a similar story.
The one exception to this was Dave Thomas's Programming Elixir book. I bought version 1.2 and he religiously updated it (for free!) all the way through its current version. I never found anything in it that didn't work on the current version of the language. Well done, Dave!
From own experience, the problematic parts are :
- deployment being a bit messy if you try to follow 12 factors (might be improving in 1.9)
- absence of a decent debugger
- younth of the ecosystem and size of the community (aka hard the find a maintained lib that works for a few common issues.)
- compiler being a bit slow to my taste (YMMV)
- then, of course, the elephant in the room: the absence of the kind of static type checking that facilitate refactoring ord relatively large codebases.
Nothing unbearable or permanent, but some things to keep in mind. Go try it !
And the post was very much intended to be enthusiastic about cool things, rather than nuanced and looking for problems. So I think your take-away is entirely fair.
- average performance ( like 10x slower than Java even worse for CPU intensive tasks )
- dynamic language ( this is the worst part ), working on large code base means problems ahead
- lot of features from BEAM / OTP that are not that useful and done better on modern cloud platforms ( Kubernetes for instance does a lot of similar things but better and more flexible, apply to any languages ) People like to talk about hot code update which imo is a terrible idea, you should have a proper CI/CD pipeline to do that and not rely on dangerous features like that.
- lack of ecosystem / libraries
- it's FP, I count that as a personal cons
IMO, I the fact that Elixir is a dynamic language is not that much a problem thanks to pattern matching.
Elixir's pattern matching is really powerful, allowing for things like:
def move(_state, _x, _y, kind) when kind not in ~w(forward backwards) do
{:error, :invalid_move_kind}
end
def move(state, x, y, kind) do
get(state, x, y)
|> do_move(state, x, y, kind)
end
In this case, I am asserting that "kind" is either string "forward" or "backwards". If not, I return the an error :invalid_move_kind. I don't need to check if pos is nil or not string, since I can assert using pattern matching that everything with my inputs are right.Also, there are things like structs:
defmodule RobotVsDinosaurs.Robot do
alias RobotVsDinosaurs.Robot
@enforce_keys [:pos]
defstruct name: nil, pos: nil
def set(state, x, y, robot = %Robot{}) do
case Matrix.elem(state, x, y) do
%Robot{} -> {:ok, Matrix.set(state, x, y, robot)}
_ -> {:error, :invalid_type}
end
end
end
What I am saying in the code above is that %Robot{} must have a :name and a :pos entries, and by default they're nil. However, to create a new %Robot{}, :pos must be different them nil. And of course, I can pattern match if my input is actually a %Robot{} and not a simply dict.You can also do crazy things like pattern matching if a byte array have some specific characteristics, like a magic number.
So while I think it would be nice for Elixir to have types (there is Dialyzer however it is kinda a PITA to use), it is less necessary than Python/Ruby/Javascript thanks to the above.
If typing is something you really want to catch at compile time, and pattern-matching and guards aren't enough for you, you can always define Dialyzer specs and run Dialyzer during your build process. I'm currently working on an Elixir codebase that does this, but I've worked on others that don't, and I haven't seen much of a difference either way. Personally, I think strong typing is overrated.
I've seen this stated many times as one of the big drawbacks of Beam languages. But using Distillery with Elixir, it's very easy to generate a release that's completely self contained. Just extract a tarball on a freshly installed system and you are ready to go. If your target platform differs from the one you are compiling your project on, there are various options for cross compiling too
mix edeliver build release production && mix edeliver deploy release production
I've set this up as an alias in mix.exs to I just have to type: mix deploy
1.9 makes configuration easier than Distillery, I think.Urgh, that's a disaster.
On the other hand, there's so many nice things that you can take advantage of without being a functional programming / Elixir god and every time you figure something out you think "how the heck was I able to survive before being able to do this?". I'm hardly an Elixir veteran but I'm past the Kool-aid phase. I still get amazed almost every day working on this project for 2-3 hours a day.
In practice, Elixir data structures are rarely dynamic in nature. All structs have the same fields. Virtually all lists and maps and whatnot you end up writing will have the same type for all elements. Unlike in the JS ecosystem, there is no culture of having functions with, say, optional arguments in the middle, or arguments that can be either a number or a function or a Date object or stuff like that. Unlike the Ruby ecosystem, there's no runtime monkey patching, runtime attribute generation, runtime anything generation. Everything is as robustly typed as your average C# program, but there's no way to write that down.
Or, well, there is, typespecs. And typespecs are imprecise, hard to write, borderline impossible to typecheck (dialyzer errors are shit), and generally just barely worth it because they're so hard to use.
It just feels like.. such a waste. Dynamic typing is nice if it lets you iterate faster, but that's nearly never the case in practical Elixir code, because there's so little dynamism and magic abound (this is a good thing!). At the same time, not being able to see what values a parameter can be, not being able to ever make proper IDE support, for a language and ecosystem that is so static in nature, is just a missed opportunity.
I still really like Elixir, and I agree with the GP's love letter, but I wish it had a friendlier way for me to communicate data structures to the program, future me, and my colleagues. I still hold hope that someone (future me, maybe?) will bolt types onto Elixir in the same way TypeScript bolted them onto JavaScript. It should be easier than TS because of how static-y the entire Elixir ecosystem already is.
(Sidenote: the usual argument against static types in Elixir/Erlang is that static type checking across process boundaries is hard, if not impossible. Genius Haskellers tried it and failed. My answer is that not having type checked messages would solve 95% of my itch. In the end, most lines of Elixir code is single-process, just transformations and function calls like in any other language. I'll be happy to tell the compiler what type I expect a received message to be and crash at runtime if it isn't - just like I do when I get sent a JSON payload over a REST API or IPC or whatever)
For example (taken from the docs on guards):
def foo(term) when is_integer(term), do: term
def foo(term) when is_float(term), do: round(term)
If you tried to pass a string into foo at run time, no function pattern would be matched and it would blow up. The above should also give IDEs a way to potentially say "hey, when you call foo, it accepts a term and expects an int or float", and it's also very human readable to figure out what you need to provide as arguments without IDE support.What's interesting about guards is you can also put expressions in there. Like `when foo > 3` and now suddenly you have a new type of integer that only accepts integers greater than 3, except it's not an explicit IntegerGT3 type you have defined somewhere.
In practice, how much worse is that vs a "real" statically typed language, other than putting guards on things is optional?
I like the convenience of deploying a golang app, just one executable.
This used to be done with Distillery[1], but I suspect its use will go down now that Elixir has native OTP releases.[2].
In either case, there's still work behind it, but it's not like deploying Ruby, Python, or Node, where you have to be pretty careful about library paths and runtime versions.
[1]: https://github.com/bitwalker/distillery
[2]: https://elixir-lang.org/blog/2019/06/24/elixir-v1-9-0-released/This is crazy. What about configuration, systemd unit file / initscript, documentation, manpage, shell completion. And the ability to tell what is installed, where, and at which version.
HN forgot how to do software distribution to the hype of statically compiled languages.
The BEAM was originally designed to run software for telephone switches. It's often referred to as soft realtime because it is so responsive. It has been battle-tested for now over 3 decades.
Where the BEAM falls flat is pure number crunching but it's blazing fast with binary processing (e.g. string parsing).
A fresh phoenix project where you render a nontrivial template easily reaches sub millisecond response times, without any kind of optimization.
To be honest, this can probably be almost 100% attributed to the fact that it is not backed and heavily promoted by a tech giant.
Edit: 4 upvotes in 4 minutes. I guess people are reading this... for anyone who hasn't already discovered it, the saving grace for me was the Elixir Slack channel. I also learned while working with someone who really knows Erlang, which helped quite a bit, too. If anyone learning Elixir gets to the point where they want to scream, feel free to email me. If I can help, I will! Email in profile.
Now, writing idiomatic functional code while coming from an OO background, now that is difficult!
I have to say though, I loved the short time I spent with Elixir so far - it's hard to put a finger on it, but it just feels right. But... I do wish it was statically typed :(
What do you mean by that? Most code in Erlang/Elixir is synchronous, meaning it will block the process (but not the scheduler). Maybe you meant concurrent (or message-passing) everything?
You can be very productive with Elixir before learning the things that it's famous for!
is the one that's in production and doing its work. Most developers including me, get bored of doing something in x,y,z framework, and we gladly go try something else for a while.
I have a good friend, that jumped on the band wagon of elixir. he openly now admits, he wish he just used python.
I hate band wagoners.. no language , no framework is the cure all.
I'm hoping to move to 1.9. The language just fit my ideology better, Jose Valim just stated that the language is mostly complete. All major planned features are completed unless something come up. The language isn't bloated, it's small and sweet, and it doesn't go out of the way to add random unnecessary features to the core.
I was fullstack since ~2008 and it is becoming pretty hard to be fullstack when frontend moves too dang fast for me. So the pace of Elixir and Phoenix is amazing. I know these two technology are relatively new but compare to its peers it's boring tech; as in it's battle proven and it's not going to radically change that often (at least not for the sake of hype or reinventing the wheel).
The community over at elixirforum is nice. There seems to be quite a few camps. The ones that stands out to me are the web dev and embedded camps.
A couple of months ago we met with a prospective client to discuss their use cases and conduct requirements gathering. They really liked what we showed them, but the CFO wanted a dashboard that displayed the data in the app in a specific way. We shook hands, told them we would contact them soon, and parted ways. It was around 9 AM when we stepped outside the client's office and got back in our cars.
By 5 PM that evening, we had a stunning, fully functional dashboard built and deployed to the demo environment. It utilized a few new database tables that aggregated data, some data processing done by Elixir, passing that data to the Vue front-end and displaying it using Charts.js and a few other UI libraries.
I sent a quick email to the CFO with the URL. He responded ten minutes later with, "holy cow, why didn't you show this during our meeting if you had it already?!" :)
We are meeting with them again later this month, hopefully to sign them on as a client.
(For reference, I've used Rails and ASP.NET with C# before Elixir, along with JQuery back in the day, and then a bit of React. Can't speak about other frameworks and languages.)
I'm also doing an startup -- we've been working on the product for only two weeks and we just released access for our first pilot customer, with an initial feature set we are very happy with. Apart from the productivity, it's been a long time since I loved programming. Keep in mind I was doing embedded C development for a few years, so my web-fu is a bit rusty lately.
The only thing I miss sometimes is types, especially when refactoring. Java with IntelliJ will spoil you, I guess. I was thinking about going with Kotlin because of this, but I was really digging the Phoenix project structure and I love Ecto.
All in all, a great experience.
Something that is great about .NET is the available tooling - the debuggers in both Visual Studio and Rider are amazing, and it's difficult to imagine living without them.
AFAIK, you're relegated to rather primitive "println debugging" with Elixir - has this been an issue for you in practice?
Not at all. The traditional BEAM way of debugging is the tracing modules. For little things an `IEx.pry()` is often good enough though.
Excuse my ignorance, but by "tracing modules", do you mean "println debugging"?
I had a quick look at IEx.pry(), which at a glace I think gives you a repl at a given breakpoint? It looks like it also requires you to instrument your code with breakpoints, which TBH feels a bit ugly (but could presumably be solved with the right IDE)
I'm an individual consultant with a very small team. Without Elixir, many projects that I've finished in weeks would have taken me months. This is a seriously under-rated language that would make you wonder why didn't you give it a shot earlier. It's that good.
My static site is now way faster than Jekyll or Middleman. I didn't re-write it for speed, speed was just a nice side-effect. I wrote it mostly for the language's flexibility.
With Ruby, which Middleman and Jekyll both use, you need to think in the traditional OOP way and sooner or later, you will hit the limits of the language itself. Whereas, with Elixir, everything is taken care of by guards. This is really one of the nicest codebases I've ever written in a while. This is in comparison to my earlier codebase which was written in Ruby, and I had to do all sorts of things like install a library to make the language more scalable. That was the ugliest hack I've ever done. [1]
Imagine, a Wordpress clone, only it runs on your computer and generates static files (this was my goal) but, written in less than a month by one person, working a full time job, with the same fit and finish of Wordpress.
Elixir is amazing.
What? You mean the generation step is faster?
Also, I recently built http://blog.winricklabs.com for example which uses my own static site generator. I didn't use wordpress just because it'd be overkill.
Our dev team seem really happy with this tech stack.
Productivity is awesome - we are four months in and already have similar functionality to a (sort of) competitor that has spent several years on their dev. This is the first dev project I have experienced where we are ahead of our planned milestones. Got to find some more features to quickly add!
My original concern was getting hold of developers as Elixir lacks the pure numbers of people that other server environments enjoy, but this has not been an issue. If anything we have got more senior devs then we would otherwise be able to get as they are excited to be able to use Elixir. Oskar in Poland and Dan in London, hats off, you are awesome!
Not sure if I agree with others that the broader environment is underdeveloped - yes there may be less versions of the same thing compared to a large JavaScript framework, but what is there is absolute quality.
Only (small) gripe is that Elixir is not a fast language. At one stage I thought this was going to be a real issue, but great support from the community and improved understanding on how to do things the Elixir way (let it fail!) seems to have resolved this for us.
Which is interesting because Elixir isn't well known for being super fast when it comes to CPU bound tasks, but for a lot of semi-CPU intensive things you'd end up doing in a web app, it's still very very efficient.
For example I wanted to generate 5,000x 19 random character discount codes and my first attempt took 730ms to generate the codes while being a complete newbie to the language and cobbling together Enum.reduce / Enum.random while concatenating strings. Within an hour of asking if someone had a better way of doing it, I got multiple solutions from community members that were able to produce the same results in 25ms while still having very readable code (arguably more readable than my original implementation), and even one person came up with a solution to do it in 3ms.
It's almost hard to imagine being in a position in a web app where 3ms would be considered too slow to generate 5,000 unique discount codes with a custom character set.
The reason I didn't use the 3ms version was due to it having too many concepts that are unknown to me. At the end of the day I would still need to maintain the code and the 25ms version is a lot easier to change (for me at least).
But, if I had very strict time requirements, I could just drop in the 3ms version at any time to get the speed boost which I think is reasonable. I only need to bring in the operational complexity when the demand calls for it. Otherwise the more human readable version is fast enough for my use case.
For example, lets say you want to compute the first million fibonacci numbers using the series' nth number formula. The function below calculates the nth fib number in the sequence; Then, to keeps things simple, we look around in the Elixir documentation and find Task which accepts a closure, is async and spawns a new process. Great you think, with the extra speed from parallelising in blocks of lets say 1k fib numbers we'll surely be faster.
def nthFib(n) do round(:math.pow(@phi, n) / @sqrt5) end
1..1000000 |> Task.async_stream(MyModule.nthFib) |> Enum.map(fn({:ok, result}) -> result end)
Nope. In fact, doing it naively with [0, 1, ... fib[i-1]+fib[i-2] ...] is faster. This was a bummer for me.
If you're interested and want to test something on hackerrank yourself, take a look here for a post I made while first experimenting with Elxir's processes on overoptimizing the first Euler problem. Noob thread here: https://elixirforum.com/t/hackerrank-optimizing-euler-proble...
Of course it might be just me, trying to apply the same principles I learned using CUDA. In my defence, those principles served me well over the years no matter if I was using CUDA or solving concurrency problems somewhere else. If anyone is interested in pitching in, I'm open to ideas, but for now I'm going to continue thinking that Elixir is fast enough for most use cases, just don't get your hopes up thinking its a silver bullet.
- LiveView (which I use in production & have recommended for upcoming projects too) is a complete game changer, not because it allows to remove javascript, but because it removes a boundary (between the client & the server), making development & maintenance much faster since you only have one layer, and also making very rich features easier, because you can remain stateful during the processing (if you have interactive rich UIs with e.g. file upload & processing then live reporting as you process the file, this will remind you of desktop programming, in a good way)
- While the initial setup of apps can be a bit cumbersome to my taste (like the SwitchTower period of Rails - e.g. you'll need a build server or a Docker image typically), the mental model of programming is quite simple in a lot of cases afterwards. I would say that junior developers can be onboarded quite easily (I'm starting to train some), and maintenance is quite sweet at this point.
I can warmly encourage you to try Elixir out (a nice way to get started by the way is to code ExUnit tests to try out the language, see https://github.com/thbar/elixir-playground/blob/master/test/... as a boilerplate to get started).
LiveView is the haven for apps that are focusing on B2B and internal tools in organizations. Because it doesn't have to support offline usage, and cost effective since you don't have to have a frontend team.
The user's actions are sent to the Backend via WebSocket, and the Backend rerenders (parts of) the view and sends them to the user.
Elixir/Phoenix/Ecto are an absolute joy.
It took a bit to get used to immutability and FP but it feels so "cozy", for lack of a better word, to know exactly what my code is doing and to not be bit by obscured mutability and magic anymore.
I can't know for sure if she was bluffing, but the idea really was interesting enough to make me wonder.
Edit: sorry, this was supposed to be a top level comment.
These are features that help eliminating uncertainties:
1. Function head pattern matching
This also includes anonymous functions used in Enumerable functions like map, reduce. Which is my most favorite way of using pattern matching
2. Guard clause
It's part of function definition so it's visible in very nice ways; not mess with the body.
3. Process supervision strategies
Let it crash! The elegant way of dealing with exceptions and unexpected errors.
It's a fair trade with static typing.
Imperfect is putting it lightly. I loathe it. Aside from useless errors ("here's what the success typing looks like! Ignore the any()s, and fix it! But I won't tell you what's _wrong_!"), it doesn't run against tests (which bit my ass in production last month due to some return values being ignored, and only actually matched in tests.)
> especially with the error message improvements available via my Erlex library
My interest is piqued. Does it help unfuck Dialyzer error messages?
That said, in a lot of other ways Haskell is not as ideal for web development, particularly if you need clustered stateful stuff.
Typescript and friends I've never really managed to develop any keen interest on, even though Typescript itself is an upgrade over JS.
I'm unfamiliar with F# and .NET stuff. C# I don't like one bit, if that's anywhere near that avenue. I've tried Reason but didn't quite click with it. Ended up preferring Elm for the frontend side, although Purescript could be even a better fit for me there.
I literally learn it on the job.
Lack of typing is the biggest issue for me, but pattern matching enable to get the shape of object and to a certain extent and I'm quite sasitify with it.
But I'd suggest reading through "Phoenix In Action" to get a feel for how everything composes together, but its surface area is much smaller than Rails (though I haven't used Rails in a decade)
Phoenix only deals with the web framework component. If you want to talk with databases, the official library is Ecto. For GraphQL there's Absinthe.
As someone suggested, check out the Hex docs. That is where you get the better in-depth stuff and API reference. I've found the Getting started-stuff very helpful but also a bit limited in scope.
Then look at the 'magic' bits. <app_name>_web.ex is an important one, and the view/template distinction can be a bit confusing at first.
From there I suppose endpoint.ex covers pretty much all the rest of it (and then hands things off to router.ex).
With Rails I was always uncomfortable that I couldn't quite follow or understand the path taken through my codebase, but with the exception of a few 'magic' things, Phoenix is wonderfully transparent in this regard.
It focuses on building a web app and shows how everything fits together while solving real issues, which is a much better learning experience than the documentation IMO. If you come at it with a Rails background you'll probably walk away with a completely different impression.
Lots of trials and errors. The one thing that I think was pretty dang unclear for phoenix is authentication.
I went through 3 libraries and scrap many codes to figure out what's what. I settle on POW, the programmer is very nice and awesome he answers a lot of questions on elixirforum.
No magic, no hacky patterns. No mess like the one you see with Node. For what it does the platform is hella stable. I drifted towards Go for a little bit but man, code in Go felt too verbose with weird patterns. Go is a solid platform as well. But it's not just my cup of tea for web apps right now.
Scalability is in reach if you need it. Hell, even if you need ridiculous background job processing power, use OTP already. And I forgot, liveView is also rock solid. Honestly, if anyone would ask me what the best platform for web apps right now is, I'd just say Phoenix/Elixir.
The immutability and the lack of magic you mention are probably the two main reasons Elixir projects are easier to jump into. Even when macros are involved, you can still scroll to the top of the file, look at line with "use" or "using" in it and know exactly what is affecting your module.
With a lot of other languages, it's completely unknowable from inside one file to know where or if external metaprogramming is affecting your module.
I've seen a few different nerves-systems targeting AWS EC2. Have you tried doing anything in particular with it?
It's just the Phoenix framework for which the initial setup of the project generator feels so opinionated. You have no options, no way to make a template for the generator. Phoenix's LiveView is a great feature and I want to use it. It's just Phoenix itself that feels off for me, not as straightforward as it should be. Does anyone else get this feeling?
I agree though that phoenix feels almost a little too heavy and opinionated.
the with syntax is nice and helps to deal with early exit on errors but still feels a bit awkward compared to imperative control flow.
like you can do something like this in an imperative language:
foo, err = func()
if err != nil {
return nil, Err("bad")
}
bah, err = func2(foo)
if err != nil {
return nil, Err("blah")
}
return bah
whereas in elixir you have to do something like the following in order to avoid the nesting of doom: with {ok, foo} <- func() |> Error.or({:error, "bad"}),
{ok, bah} <- func2(foo) |> Error.or({:error, "blah"}), do
bah
end
like the with blocks kind of work until you have to transform the errors you receive then you need helper functions. if you are just doing static transforms like above it is not too bad but it starts to get hairy if you want to transform based on the returned error or variables in the function. whereas the imperative style you can inline your error handling logic nicely into the function.for example what if i want to log something on the error path that includes some contextual information and custom formatting. probably, the easiest way is going to be to use with() and pipe to a custom function that triggers on the error path to do the logging because the code is going to start getting really messy. whereas if i was writing it imperatively i could just inline the logging statement most of the time because it is just a few lines of code.
foo, err = func()
if err != nil {
return nil, Err("bad")
}
bah, err = func2(foo)
if err != nil {
Logger.error("err: " + err + " when processing: " + foo.name)
return nil, Err("blah")
}
return bah
like i feel this is a bit messy but maybe it is actually not that bad: with {ok, foo} <- func() |> Error.or({:error, "bad"}),
{ok, bah} <- func2(foo) |> Error.or_else(fn err ->
Logger.error("err: " <> err <> " when processing: " <> foo.name)
{:error, "blah"}
end), do
bah
endI've been using Elixir and Phoenix for a customer for a couple of years. It's ok to great, especially when spawning jobs, with some stains.
I'm not a great fan of the with syntax. I wish they implemented it as a native statement of the language instead of as a macro. In that way they probably could let us write the same code inside and outside a with, instead of having to transform = into <- and add a comma.
But the worst offenders are GenServers. They should really have the syntax of OO classes instead of the incomprehensible handle* functions. After all that's what they are, objects with their own CPU. (Remember Armstrong about Erlang being the only true OO language?)
By the way, that would make it easier to code, to understand and to migrate people from imperative languages.
Furthermore GenServers mix client side and server side code in the same module. It's very confusing even after years. It's one of the most unpleasant coding experience of the decade for me.
On the other side I'd steal Elixir's pattern matching implementation and add it to every language. It's everywhere in Elixir and IMHO it's its strongest point.
with {:user_created?, {:ok, user}} <- create_user do
# do something with `user`.
else
{:user_created?, {:error, errors}} ->
# something
_ ->
# some unhandled error
end
And so on, use an atom on the fly to identify branches and error conditions. But honestly most of the time you worry about happy paths and Let It Crash.I would also welcome a better built-in idiom for early returns.
On a "normal" language you have to deal with all error paths or your app goes down. On the BEAM you handle the happy case and common and unexceptional errors. Otherwise, let it crash.
Example: if your app depends on a database that once in a blue moon is unreachable, don't test for connection errors. Just assume the connection was successful, and if it wasn't, most of the time once the process restarts everything is fine.
I have an Elixir app in production, I get Sentry errors once in a while about some weird state outside my control (we work with external APIs) that caused a process to crash, I just ignore them and go on with my life.
EDIT: I highly recommend this video from Saša Jurić: https://www.youtube.com/watch?v=JvBT4XBdoUE
A while ago I wrote some code that retrieves data from various online sources (cryptocurrency exchanges) at regular intervals. A friend of mine wrote essentially the same code in Python. His code was littered with try/catch statements and even with those the app would often crash because these API's sucked ass. As a result, there'd be gaps in the data, or he'd have to restart the app or set up whatever restart mechanism one uses in the python ecosystem.
Meanwhile my elixir project just kind of kept running and retrieving data, and barring permanent changes in the various API's, it would keep collecting data even in every once in a while the endpoints would misbehave.
My typical approach to projects is to tinker and cobble things together but then also overly worry about all the things that can go wrong. I know I'm not alone in being this way; I've met plenty of developers who seem to be a combination of just wanting to get results but then worrying excessively about everything that could go wrong.
Elixir is singular in how it allows me to approach projects in this manner while still feeling confident that it'll work well enough. And while that might not be the most common use-case, it's really helped reinvigorate my enjoyment of programming.
With very little effort or development time we where able to put together a highly scalable solution that is robust and very low maintenance.
The erlang Vm’s roots go back to telephony switches, so there are many cases beyond web.
My current favorite things in Elixir are not particularly web-related:
- Nerves, embedded Linux + the BEAM VM to do IoT-style things in a nicer way. The workflow compared to something like working from Raspbian seems a lot more sane to me.
- Scenic, OpenGL-rendered UI, for embedded hardware or other purposes. I recently used it to get text-rendering and geometries onto an eInk display with Nerves. One big reason for the creation of Scenic was to give IoT/connected devices UI that doesn't require a web stack. For many reasons, with security definitely being high on the list.
I tried learning Elixir a while back and just couldn't get myself to like the syntax/ergonomics. It seems like most of the benefits people list for Elixir are actually attributed to BEAM, not the language itself.
In my opinion OTP/BEAM is the killer feature of Elixir; however, there are a lot of other niceties as well. Macros, pattern-matching, tooling, readability, similarity with Ruby (a plus for Ruby developers) all spring to mind.