Redux for the Perplexed

I was working at Facebook in 2015, I believe, when I asked my manager for a temporary transfer to a team that was working with React and Flux. Back then, looking at this new pattern, I was somewhere in between of being amazed and perplexed. Like, what is this thing, just why? Nowadays fewer projects use Flux since the invention of Redux, which is pretty similar to it, just simpler. If you feel the same way about it the way I felt about Flux, this article is written for you, to aid your entry into the world of this amazing way of application state management.

Intro

At its core, Redux is just a simple little library, maybe call it a design pattern, which will help you manage your application’s state. Things such as values inputted in a form, or the list of names shown in a table. It does this by storing all of the state into one giant, nested object. The state object is immutable, the view layer of your application cannot directly alter the model of the application, nor can one part of the model update another part of the model. All updates of the model are happening at a neatly collocated space, called the reducer function, and it always happens in a unidirectional, so called, dispatch cycle. If that all makes sense – congrats, you need not necessarily read any further. Check out the official Redux documentation and jump right into it. If however, you are still perplexed (like I was), keep reading…

Comparison with MVC

Tell me, do you know what Model-View-Controller a.k.a. MVC is? Think about it then keep reading.

To my understanding, it consists of (obviously) three things:

  1. Something about having an object which holds raw data, the primitives, also known as the model.
  2. Another thing which shows the model to the user, known as the view.
  3. Controller, which reacts to user’s actions and updates the model, which then updates the view via a set of listeners.

In MVC, data flows around from model to view, from view to controller, then from controller to model. And back again. In addition to that, one model object can subscribe to another model object, pretty much everyone can read, subscribe and alter the model, and so on. This can lead to a messy event propagation through your application state, including infinite loops and whatnot. Very complex to debug.

Redux solves the same problem as MVC does, except that it avoids the infinite loops and “everyone can update the model however they want” part. It’s concerned only with the model, and partially with the controller – the part where controller updates the model. It also makes sure that each state is well contained – just like a React component is – nothing outside of it can affect how it manages it’s data. So what does it have instead?

  1. It has a state, which is roughly equivalent to the MVC model – a plain, preferably immutable, JavaScript object.
  2. It has actions (similar to a controller), which describe events in the system that should trigger model updates.
  3. Finally, there is the reducer (also similar to a controller), which is simply a pure function that explains how an action affects the state.

The coupling between the model and model controller is much tighter here. This makes it much easier to encapsulate (in code) where and how does model change with each action. You no longer can have one model subscribe to another and trigger an avalanche of chained updates, including the dreaded infinite loop.

Before jumping into more theory, let’s take a look at some code…

Writing a reducer using Ducks

There are actually multiple styles around regarding how do you write Redux code. The one I’ll present here is the ducks format, which is rather collocated form of writing Redux. A “duck” is a file which contains three things – action types, action creators and a reducer:


// ./app/ducks/document.js

// 1) Action types usually are stored in a constant
// Prefixed by the Duck name.

const DOCUMENT_CHANGE_TITLE = 'document/changeTitle';

// 2) Action creator is a function that returns an action.

export function changeTitle(newTitle) {

  return {
    type: DOCUMENT_CHANGE_TITLE,
    newTitle,
  };
}

// 3) the meat of the duck - reducer.
const INITIAL_STATE = { 
  title: '',
};

export default function documentReducer(
  state = INITIAL_STATE,
  action, 
) {

  // Check whether this action affects our reducer.
  switch (action.type) {
    // If the action is one of our own, then yes.
    case DOCUMENT_CHANGE_TITLE:
      return {
        ...state,
        title: action.newTitle,
      };
    // Otherwise we don't want to change the state.
    default:
      return state;
  }
}

Alright, make sure to read the snippet above and understand as much as you can.

To put the above code into words – by Redux design – whenever something happens in your app (user enters a query, clicks a button etc) – you will fire off, or dispatch, an “action”. More about this later. Action is just an object with the type property. This action will then be sent to all the reducers. That’s important to notice. This is why our reducer has the switch statement – to filter out all other actions which are not meant for this reducer.

To go into details, let’s look at each of the parts individually:

  1. Here we specify which action types exist in this ducks file. Our has only one – the DOCUMENT_CHANGE_TITLE. Usually, they are prefixed with the duck name (“document”, you can also see this in the duck name – document.js) and suffixed by the action purpose (“change”, as this action is about updating a value) and target (“title”, as we want to change the title). By default, this constant is not exposed, but it can be made so if we desire other reducers to be able to react to this action event as well.
  2. The action creator is an exposed function. This is what external components (e.g. React) will use to communicate their intention with the reducer. This is how you trigger state updates. Simplest action creators just return a simple object with a type property, which hold one of the values from the action type constants. These functions don’t have side-effects – they don’t change anything outside of their scope (or at least not until they have been dispatched, in case of redux-thunk library, which will is an extension of Redux).
  3. Reducer is the glue which combines all different action types into one state object. It’s literally a reducer, in the functional programming sense, taking the previous state and next action event, and reduces them to the next state. It is important to notice here that the input state object is not modified – instead it is cloned into a new object by using the spread syntax (three dots).

Redux store

Once we have all these reducers / ducks written out, we need to combine them into a store.


// ./app/store.js

// 1. Import redux.
import { 
  createStore,
  combineReducers,
} from "redux";

// 2. Import our ducks
// The first one is our example above,
// others are left to your imagination.
import document from './ducks/document';
import notifications from './ducks/notifications';
import session from './ducks/session';

// 3. Export a store creating function.
export default function createMyStore() {
  return createStore(
    combineReducers({
      document,
      notifications,
      session,
    })
  );
}

Again, make sure you read and understood as much as you can.

To put the above code into simple words, we’ve just created a function that will help us create that large, nested, state/model object – also known as the store. We do this by taking a bunch of reducers and combining them into one. The store object has two things – not mentioned above – the getState and dispatch methods. Calling getState will produce an object that has three keys – title, content and notifications, each of which will hold its corresponding state object as described by each reducer.

So if anyone wanted to know what the current title is, they would have to access store.getState().document.title. First layer of that access pattern is always calling the store’s getState() method. Second layer is the reducer’s name – document. Everything else remaining is accessing the desired property from our document state – title. This is the case when using combineReducers such as above.

To go into details, let’s examine each of the steps:

  1. This basic example includes importing the createStore function and combineReducers function from the Redux library. There are others, for more advanced examples, such as applyMiddleware and compose etc. Thing is, they are all much simpler to understand once you know the basics. We will use these two functions later.
  2. Now we import our ducks / reducer functions. Each duck will later become part of the store, by using the Redux functions mentioned above.
  3. Meat of the store creation is combining the createStore and combineReducers functions. Former one creates the store – an object which has the getState method, for fetching the current state, and a dispatch method, for firing off new action events into the store’s reducers. Since createStore works with a single reducer only, we need to use the combineReducers method to combine our multiple reducers into one big reducer. Effectively in the store’s state, it will produce an object that will be keyed by the reducer name, and a value which will come from the reducer’s state.

Dispatch cycle

Finally, how does one communicate with Redux? When you need to render your view, the data is then fetched from the store using the getState method. When a user does something on the app that should affect the state, you will communicate with the store through it’s dispatch method. Usually, projects will initialize their store at the application bootstrap and keep it in a singleton. Then they will use a wrapper library, like react-redux to “connect” their components with the store (both dispatch and getState), so that it removes some boilerplate. But without going into depth of such libraries for different UI frameworks, in it’s core, this is what happens:


// ./app/application.js

import createMyStore from './store';
import { documentChangeTitle } from './ducks/document';
 
// 1. Initialize the store somewhere in your code, once:

const store = createMyStore();

// 2. Dispatch an action from your controller:

store.dispatch(documentChangeTitle('Hello World'));

// 3. Obtain the new state, from your view:

console.log(store.getState().document.title);

The example above has three parts, which are usually not all in the same file in a real world application.

  1. Initializing the store is as simple as calling the store creator function. You keep this store somewhere in a singleton so that the entire app can access it. Preferably you will use your framework’s extension library to manage the store, such as react-redux.
  2. Altering the state is possible only through the dispatch method. You basically construct your action object using an action creator (documentChangeTitle in this case), describing what’s changing, and then let the store know about it using the dispatch method. This will trigger all reducers in your application. Only the reducers which care about this action (document.js) will react to it – and as a result the internal state of the store will change to reflect this action.
  3. Getting the store’s state (model) is as simple as calling getState(). Then you navigate through the returned object’s layers to find the value you need. This is something an MVC view would do, most commonly.

The dispatch cycle is basically this pattern of dispatch, getState, dispatch, getState… There is no other way to change the store’s state, nor to retrieve it, than through these two methods. This is what makes the data neatly encapsulated and unidirectional. The actions flow from your application’s event handlers to the reducers, which update the store’s state, which causes the presentation layer to change, and all over again.

Conclusion

Hopefully by now you have a better idea on what Redux is, how it compares with MVC, what does it generally look like and you are no longer perplexed.

Finally, if you have any questions or doubts about Redux, I highly recommend going through the official Redux documents to expand on your knowledge at https://redux.js.org/api as well as feel free to shoot me an email at sreckotoroman@gmail.com

Solving a Bad Scrum (TM)

In the programming world, Scrum is known as a development process technique – a way of organizing how work is done! There are plenty of articles out there, but here’s something of my own perspective on things.

I’ve been a Certified Scrum Master by cPrime since 2015. I’ve worked for multiple scrum teams in different companies. Here are the common pitfalls I’ve seen in my experience, and how to avoid them.

Let’s kick off with a…

NFL Ref Meeting - stand up update: yesterday... ... all my troubles seemed so far away...

Too long of a daily stand up

Problem: Some folks like to run daily stand up meetings that last far too long – sometimes more than an hour. It happens, believe me, I’ve seen it. People get caught up in problem solving, doing a little bit of design discussions, a little bit of project planning, few debates about favorite coding environments and so on. Poof! One hour gone. That’s, on an 8 person team, about one engineer worth of time lost every day. Well, truth be told, some of these discussions can be productive, still, is the trade-off right?

Solution: First of all, analyze what’s causing it – what is the reason behind the long stand up. Is it the lack of awareness in the team that stand-ups are more productive if kept quick? Is it the Scrum Master, Product Owner or the Manager who likes to keep tabs on everything? Is it that there is a lot going on and people need to discuss a lot of things that are on their minds? Once you’ve done that, work with the team to show how much that reason is costing them – in time and efficiency. Offer to run a different kind of a stand up – one where (as suggested by pretty much everyone) people quickly just acknowledge each other on three things – what has been done last day, what is being worked on today, and are there any blockers. One minute per person, tops! Break up after the quick meeting and discuss anything you have with individuals, if needed. Congratulations, you’ve just saved your team tons of productivity.

No stand up

Problem: Some folks run “Scrum”, but without a daily stand up. Perhaps they don’t have stand ups at all, or they run a weekly stand up, or something else. This is far better than the previous problem, of having too long of a stand up, but is it good? Stand-ups are like brushing your teeth – it’s a morning routine, good for your team’s health. Now, I don’t have any data to back this up, so you will excuse my “proof-by-common-sense” here I hope, but, having a stand up is a great way to make your team feel like a team. People make eye contact, everyone gets a chance to speak up, everyone gets heard, positive energy is exchanged, camaraderie is built etc. That’s what a good daily stand up does for your team. It’s a useful, affordable routine, when done properly – quickly and consistently.

Solution: What is the reason behind not having a stand up? Does the team feel negatively toward meeting every day? Do they feel there aren’t enough many updates to be shared every day? Is it that everyone is working on a separate track? Perhaps you don’t need it after all? If you think otherwise, and would like to fix this problem, try offering to your manager to talk to everyone on the team and find out about their sentiment on daily stand ups. Figure out where you’re at. Address the concerns using some of the values mentioned above and propose a solution to your team. Offer to run a daily stand up for one week, and see whether the team’s sentiment changes.

Next we have…

Rent Is Too Damn High - our product backlog is too damn long!

Humongous product backlog

Problem: Your team’s backlog has several hundred stories in it, nobody knows what lurks in there and it just keeps growing (i.e. new stories are added faster than old stories are being closed). It’s not prioritized ranked (because it’s impossible to do), half of the items are deprecated since last year and the rest is so poorly documented nobody understands what they are all about any more. Its purpose has come down to serving purely as an excuse of a backlog, something where you put stories and hopefully never have to look at them, ever.

Solution: Start fresh, unfortunately, is your best bet. With your next, fresh backlog, use the following recipe to make it end up not-like-your-old-backlog.

  1. Rename your existing backlog to Unplanned. That’s your graveyard of stories anyway, things that aren’t on your roadmap and who knows if they ever will.
  2. Create two additional folders for your stories: Planned (this is where you will build your fresh backlog) and New (this is where people add stories which are not refined yet).
  3. Keep your Planned backlog ranked, not prioritized, i.e. do not have “High”, “Medium” and “Low” stories. Rather, have them numbered, e.g. from 1 to N (the number of stories in the backlog).
  4. Limit it to ~50 stories, so that anyone, especially the Product Owner, can have at least some idea about what’s in there.
  5. Start by polling the stories you think you will be working on in the next 3 months, but no further than that. Sift through your old backlog, check with the team, managers etc. Put them into the New folder.
  6. Schedule a backlog grooming meeting. In this meeting, go over the New folder and make sure all stories are:
    1. Estimated – for example using Fibonacci’s complexity points. I prefer using 1 for anything that’s easy (relatively a day or less), don’t go more granular than that. The 1, 2 and 3 are “small” stories – workable by a single engineer in a single sprint – anything bigger than that either needs to be broken down (as the time comes for you to work on it), or it needs more than one engineer to work on it during the sprint. This is just an example of how to do this estimation, pick your poison.
    2. Formatted – the story beings with a customer in mind – As a <who?>, I want <what?> so that <why?>.
    3. Detailed – the story has acceptance criteria – basically think of it as a break down of requirements. Sometimes, it’s like objectives and key results. E.g. if the customer wants a new car, the acceptance criteria might contain that it must be fuel efficient, or that it must be black, etc. Don’t go overboard with this.
    4. Ranked – compared with the rest of the stories in your Planned backlog (which is initially empty), assign a number to it, from 1 to N. Fractions are okay when you are okay during the grooming meeting, but at the end of it, you should reorder all stories back from 1 to N (e.g. 1, 1.5, 2 becomes 1, 2, 3).
    5. Repeat and rinse weekly.
  7. Sprint planning? Pick your top stories from the backlog (more or less, things oftentimes changed since the last grooming meeting) and run back to work!

No backlog whatsoever

Problem: Some folks like to keep it informal. This is, again, not as much of a problem as keeping a bogus backlog around. Less overhead. Still, you are probably missing out on a good technique to keep everyone focused. You can’t answer things easily such as “when will this get done?” (assuming you are not going to do it right now), “what’s on your roadmap?” etc.

Solution: Figure out what’s the reason behind this. Lots of people have never seen a functioning backlog (check the previous situation and the award winning recipe). Perhaps people are “too busy”. Etc. Offer to create a backlog for the team and manage it for some time, and see whether it works.

Finally, with so many meetings (grooming, planning, daily, retrospective, demo), there’s one common problem of…

First World Problems - in a scrum meeting again and i forgot to bring my laptop

People are bored to death by your Scrum

Problem: Lots of people love to run meetings, and I can’t blame them for it (I’m one of them). It can be a fun, dynamic, fulfilling, and as one meme said, “excellent alternative to doing actual work”. Your hold your Scrum meetings, but you notice your team is on their phones, laptops, nobody is paying attention, everyone hates it, yada-yada-yada.

Solution: Fix yourself! The team is not at fault! Understand why do people prefer the alternative to listening to your meeting. Are you engaging with the audience enough? Do you ask questions, even rhetorical ones? Do you change your intonation when you speak? Is your meeting too long? Did you ever ask the team what they think? Does this meeting produce any value? Whatever you do – don’t keep your meetings longer than 45 minutes. Keep the last 15 for Q/A, or let folks off the hook early – everyone loves that. If you are in the position of leading these meetings – make it a priority that everyone else gets an equal chance to participate.

Thanks for reading thus far, please do share what other problems & solutions you’ve seen in Scrum teams and lastly, if you and your team really can’t stand doing Scrum, but you are doing it because everyone else does – the quick tip is – you don’t have to do Scrum – at all. And you are not alone in this. One of the people I admire the most in this world would agree with you – Erik Meijer:

Linux Guitar Pro Alternative

Today I finally configured my Ubuntu for guitar tabs playing!

Here is the recipe:
– install “tuxguitar” package
– install “timidity” package

Maybe your sound card supports MIDI files better than mine, so you might go with hardware support for playing MIDI files. However, software sequencers do provide better sound and sometimes they are the only choice, as in my case.

For some reason though, timidity daemon isn’t started with boot up, so I had to start it manually. Before launching tuxguitar, launch following command from terminal:

timidity -iA -B2,8 -Os -EFreverb=0

Then run tuxguitar and select Timidity port from the settings as shown in the second picture.

Good luck and enjoy your guitar 🙂

TuxGutar

TuxGuitar settings
Configuring TuxGuitar to use Timidity synthesizer

Debian Squeeze/Sid Java networking issues

I’ve moved from 32bit Ubuntu 10.04 to a 64bit Debian Squeeze recently. No important reasons for abandoning Ubuntu, I just felt more like going Debian for a change. Unfortunately, I run into a new kind of bug when I tried to install some Eclipse plugins, and it turns out that all Java networking is broken…

Continue reading “Debian Squeeze/Sid Java networking issues”

Rooting HTC Magic 32A/EBI1

I’ve rooted my HTC Magic, so here is a short tutorial on how I did it. It was very easy actually.

Please, if you are unsure of what you are doing, don’t follow this guide and cry to me later if you brick your phone. This guide is for HTC Magic 32A, and tested only on models available in Serbia.

You will need to download a couple of files, and the most important thing is the first one – Amon RA recovery image. I really can’t explain now how much this image eases the flashing of Android phones. Also, RA comes with Nandroid backup (so you can always “undo” if something goes wrong) and SD card formatting utilities. Anyway, on this forum thread you can read which recovery image is suitable for your phone – for mine, it was the recovery-RA-sapphire-v1.7.0H.img

Now, before downloading ROMs and other stuff, lets first flash that recovery image to your phone. This used to be done via adb utility, but someone has created a phone application that exploits bluetooth buffer overflow, so the image can be flashed via phone. Copy the recovery image to your SD card, name it shortly, say “recovery.img”, and then (on your phone) run the FlashRec application. It should say here that you have a “EBI1” phone, don’t continue if it says otherwise and skip this tutorial coooompletely! First, do a backup (because your phone already has a recovery image, but it is not this good), and then in the text box type /sdcard/recovery.img and the click Flash button.

Suppose that step ended successfully (if it didn’t, don’t ask me what to do about it, GIYF). What you have now is a special recovery image with the root access to your device. Recovery image is started by shutting down your phone, and then pressing the green Home button and red Power button together. Press it, and keep them pressed until screen turns on. If you’ve done everything right, soon you should have a recovery screen (somewhere in the bottom should be written “recovery image 1.7” or similar).

First, do a nandroid backup. You will see it in the menu. Then restart your phone (normal way), connect it to USB and copy the nandroid folder from your phone’s SD card to your computer, so that you can always go back if you screw up something with roms.

Now is the time to download ROMs. I used Cyanogen 5.0.7 ROM which is Android 2.1 codenamed Eclair. It is uber fast and I haven’t found a single bug yet. There are four files that need to be downloaded. First, the rooted  Android 1.6 ROM from HTC. Then, the cyanogen mod ROM, followed by a new kernel, and then finally google apps, which are for some reason not included in cyanogen ROM mentioned before. There are other ROMs (including Cyanogen’s) which include google apps, but I won’t discuss them here now. Copy all four zips to the SD card.

Reboot your phone to recovery mode. From wipe menu, choose reset factory settings. Then wipe your dalvik-cache. Since this is your first flashing (I assume so in this guide), you don’t need to wipe anything else. After that, return to the main menu, and apply the downloaded ROMs using “flash zip” option from the menu, in the order you downloaded them, that is:

  1. HTC_ADP_1.6
  2. update-cm-5.0.7
  3. bc-5.0.7
  4. gapps-ds

Reboot your phone, wait a little while until dalvik-cache is recreated, and enjoy your new operating system 🙂

Most of the credits goes to @Cyanogen, Amon RA who repacked his recovery image, bcrooks who packed the kernel and guys behind the flashrec utlity who saved our a**es from using fastboot (totally eliminating the need of a personal computer during flashing).