7.3

Restructuring Code

For the remainder of this chapter, we’ll be exploring how to send the POST, PATCH, and DELETE HTTP requests to create, update, and delete posts respectively. Before we do that though, we need to restructure the code in DecodingJson.elm. It has reached a point where breaking it into smaller modules will make adding new features easier.

The recommended way to manage data flow in an Elm app is to use the Elm Architecture. Elm doesn’t have such a recommendation when it comes to organizing code, so we can structure our code however we want. There are many different ways to do it, but we’ll follow the suggestion from Evan Czaplicki — the creator of Elm.

Per Evan’s advice, all modules in an Elm app should be built around a central type. That means we should create a separate module for each page in the posts app. Currently, we only have one page for displaying posts. Soon we’ll add more pages for creating and editing posts.

The central type for each page module will be Model. The page modules will also be provided with separate init, update, and view functions. That will enable them to independently follow the Elm Architecture. The idea here is to let each individual page manage itself.

Any common data structures such as Post will also get their own modules. Finally, we’ll wire everything together in the Main module which will also have its own Model, init, update, and view functions. The final directory structure will look something like this:

Don’t worry if some of this doesn’t make sense yet. In the following sections, I’ll provide step-by-step instructions to guide you through the entire process of transforming the code in DecodingJson.elm to a more robust structure that will allow us to add new features and modify existing ones with ease.

Back to top

New chapters are coming soon!

Sign up for the Elm Programming newsletter to get notified!

* indicates required
Close