Reviewing ports with elm-review

I wanted to share with everyone some elm-review rules I’ve written for reviewing Elm ports and hopefully avoid a few pain points that I’ve come across learning to work with ports.

elm-review-ports

There are three rules in the package so far:

  • NoDuplicatePorts - Ensure that port names are unique across your project.
  • NoUnsafePorts - Forbid unsafe types in ports.
  • NoUnusedPorts - Ensure that all defined ports have been used.

NoDuplicatePorts

As the name says, this rule checks for any duplicate port names in your project. When there are multiple ports with the same name you may encounter a javascript runtime error. I got one of these and it took me a little while to track down because I was writing Elm and wasn’t expecting to have a javascript runtime error so I didn’t immediately look into the javascript console.

NoUnsafePorts

Inspired by the information about Verifying Flags in the Elm guide, this rule reports any ports that do not send or receive a Json.Encode.Value. You can set the rule to ignore outbound ports - since it’s a little safer to let javascript worry about type handling. This has been great for me already and has made me think about what I’m sending through my ports and how Elm can handle it best.

NoUnusedPorts

This rule reports any ports that are not used anywhere in the project. A port is only considered used if it can be traced to a main function. Elm is very good at eliminating dead code from the compiled JavaScript. When a port is unused it will not be present in the compiled JavaScript, and when no ports are used the app.ports object will be undefined. This can lead to JavaScript runtime errors that could take you some time to figure out.

This was a surprisingly tricky rule to write as it takes quite a lot of effort to trace a function all the way to main. One bonus of doing this though is that the rule can point at where it lost the trace. Here’s an example of what that report looks like:

17 Likes

Nice! This is a step further into type safety! Is this intended to execute always while in development, or just sometimes to check? What is the average execution time of those rules?

I think that depends on your workflow. Although elm-review isn’t quite ready for IDE integration yet, it does come with a watch mode that can happily sit in a terminal watching for changes in and reviewing your code. I personally use it as an occasional check, along with other rules to check that I’m meeting my personal code standards, I try to leave the watch mode running so that I’ll see any reports when I flick back to my terminal to commit my changes. I’ve also got elm-review in my CI checks.

I’ve been following elm-review, but would never had thought of this use! What a great way to ensure good guarantees even on the edges on of the Elm runtime.

2 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.