- By Javier Martínez
- ·
- Posted 10 Aug 2021
Functional patterns
Welcome pythonistas! In our last video session on design patterns we focused exclusively on patterns for the object oriented paradigm (OOP). To some..
Table of contents
The requirements come, we have some UI mockups and now we need to start developing a web app. What is the first step we need to do?
Let's go back a bit. If this was not a specific web app but rather a generic one, then:
In the following lines I will try to address exactly this questions. We'll start with a little bit of theory, then we'll put it in practice:
We'll have to think a bit strategically and a little bit tactically. For the strategy, what would be our goals:
Ok, but how can this be done?
Well, we'll do it in 4 Steps:
Steps don't need to be sequential, in fact it is recommended to do the last two in parallel.
We will be using a few patterns:
and a few Techniques:
We'll rebuild the famous TodoMVC web application (even though some people suffer from TodoMVC fatigue), focusing on what we said before.
So let's start with Step 1 - Finite state machine
Our purpose is to create a state diagram with all the states and transitions we think we'll need. This is not an easy step, but it can clarify the entire development process further on. Let's see what can be done.
Actions:
From the screens it also look like we'll have the following States: list (filtered or not)
and now let's put it in a diagram:
Now using this diagram we'll move to step 2 and we'll do the code according to it.
We will separate the different concerns using the MVC pattern. All the logic will be in the controller, the data in the model and we'll add the presentation later (or someone else could do it in parallel).
Our data will have to be able to represent all the states in the diagram above: list/filter, add and edit
;What is a todo?
{:text "todo", :done? true}
;How do we know the status?
;When do we filter?
{:context {:status "list"
:filter true}
:todos [{:text "todo 1" :done? true}
{:text "todo 2" :done? false}]}
;What about edit?
;How do we know which do we edit?
;How do we order the todos?
{:context {:status "edit"
:filter true
:selected-id 1},
:todos {
:1 {:id 1, :text "todo 1", :done? true, :time 1}
:2 {:id 2, :text "todo 2", :done? false, :time 2}
}}
;Let's carve it in stone: (require '[clojure.spec.alpha :as s])
;SPEC
(s/def ::status #{"list" "edit" "add"})
(s/def ::filter #(or (false? %) (true? %)))
(s/def ::filter-with-nil #(or (nil? %) (false? %) (true? %)))
(s/def ::selected-id nat-int?)
(s/def ::context (s/keys :req-un [::status] :opt-un [::filter-id ::selected-id]))
(s/def ::id nat-int?)
(s/def ::text string?)
(s/def ::done? boolean?)
(s/def ::time number?)
(s/def ::todo (s/keys :req-un [::id ::text ::done? ::time]))
(s/def ::todos (s/map-of keyword? ::todo))
(defn edit-mode-has-a-valid-selected-id? [state]
(if (= "edit" (get-in state [:context :status]))
(some (into #{} (map :id (vals (:todos state)))) [(get-in state [:context :selected-id])])
true
))
(s/def ::model (s/and (s/keys :req-un [::context] :opt-un [::todos])
edit-mode-has-a-valid-selected-id?
))
(comment
(s/valid? ::model {:context {:status "edit"
:filter true
:selected-id 1}
:todos {
:1 {:id 1, :text "todo 1", :done? true, :time 1}
:2 {:id 2, :text "todo 2", :done? false, :time 2}
}}))
Now we know how we could represent our states as data in the model, let's test drive the different transitions which will al be functions in the controller. Normally I start with a plan, where I will know what I want to test.
The plan of the tests:
Then we'll write the first one:
(deftest initialize-in-list-mode
(is (= {:context {:status "list"} :todos {}}
(init!))))
which will obviously
Test fails! Good... now we write the code to make it pass:
;THE MODEL
(def model (atom {:context {:status "list"}}))
;THE CONTROLLER
(defn commit! [value atom-to-change]
(reset! atom-to-change value))
(defn init! []
(-> @model
(assoc :todos {})
(assoc-in [:context :status] "list")
(commit! model)))
;THE TEST
(deftest initialize-in-list-mode
(is (= {:context {:status "list"} :todos {}}
(init!))))
Any refactorings? No, let's move to the second test and so on until we solve the entire data problem, one test at a time, making sure it fails, then making it pass, then refactoring the code. We end up with this:
Solve the data problem (TDD the model/controller) Done!
The code is merged here: https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps/merge_requests/1/diffs
Code:
Now let's have another look again to see the correspondence between the transitions and the controller functions:
while the data in the model corresponds to:
It is also worth mentioning that we're using the Reagent library, where the model is an atom that is watched for changes. When the atom is changed (in our case by the controller functions, thus the transitions) it will tell the UI to repaint.
We will need now to make sure that our states can be represented on the screen.
For instance when we're in list mode, filtered:
How about edit state:
Now that we know how the data corresponds to the UI, we can move on to doing the actual UI. We'll use react/reagent to break the UI into components:
screen_component
todo_input_component
text_input_component
todos_list_component
todo_list_item
todos_count_component
todos_filter_component
The final version will be like:
Then we'll test drive the entire UI starting by planning the tests:
It is worth mentioning that TDD-ing the UI can be split into two types of tests: - render tests and - interaction tests
For the render tests you send some data to your components, render it then check how it's rendered. We start with a render test (we'll use enzyme):
(deftest render-the-main-screen
(testing "render all sections"
(let [component [views/screen-component data/one-todo-list-mode-no-filter]
mounted (->> (r/as-element component)
(.mount js/enzyme))]
(is (= 1 (-> mounted (.find ".header") .-length)))
(is (= 1 (-> mounted (.find ".main") .-length)))
(is (= 1 (-> mounted (.find ".footer") .-length)))
(is (= 1 (-> mounted (.find "li.todo") .-length)))
(is (= "0 items left" (-> mounted (.find "strong") .getDOMNode .-innerText)))
)))
the test fails, so then we start writing our first component, making it pass, refactoring etc.
For the interaction tests, you render some data, then click a button and make sure the mocked function that should be invoked is actually invoked:
(deftest invoke-controller-filter-when-clicking-filters-in-todos-filters-component
(let [invocations (atom [])
component [views/todos-filters-component nil]
mounted (->> (r/as-element component)
(.mount js/enzyme))]
(with-redefs [controller/filter! #(swap! invocations conj [%])]
(testing "unfilter"
(reset! invocations [])
(-> mounted
(.find "#all")
(.simulate "click"))
(is (= [[nil]] @invocations)))
)))
The code is merged here: https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps/merge_requests/2/diffs
Code:
The complexity problem -solved by making a state machine and using separation of concerns.
The Robustness problem - TDD is a clear step forward but we can go further:
But that will follow in part II.
Welcome pythonistas! In our last video session on design patterns we focused exclusively on patterns for the object oriented paradigm (OOP). To some..
Solving a simple problem in Elixir In this article, I am going to solve the Word Count problem from Exercism in Elixir. I'll start with a form that..
Bank kata in haskell - using and testing date Recap Last post we looked at printing whilst holding state. Here's the code we ended up with:
Join our newsletter for expert tips and inspirational case studies
Join our newsletter for expert tips and inspirational case studies