Confident React App – Part 5

Here we go again! The “Confident React App” series of posts is finally back after a long period away. You can follow from the start.

From the feature specs – defined in the 1st post of the series – we can observe some important information regarding interactions:

  1. list item selection is toggled when clicked.
  2. the list group works with a single selection of list items.

The second point was not explicit from the specs (and it was intentional so that you could comment on it. Did you notice it?) but we discovered it after some (imaginary) team discussion (backlog grooming, pre-iteration meeting, etc). The team must extensively communicate verbally and written in preparation for the implementation. Many questions arise when the code gets written, especially in the early stages of development. Effective communication is key!

With that in the clear, it’s time to start coding the user interaction of our app.

Oh, behave…

We’re introducing a new component which whole’s responsibility is to handle user interactions and state management: <SingleSelectionListGroup>.

We’ve “transformed” the component’s specification into tests:

// src/components/listGroup.spec.js
// @flow
describe("<SingleSelectionListGroup />", () => {
  it('renders according to specification', () => {});

  describe('when an item is clicked', () => {
    describe('and it is NOT selected', () => {
      it('selects the clicked item', () => {});
      it('deselects any other selected item - single selection', () => {});
    describe('and it IS selected', () => {
      it('deselects the clicked item', () => {});

    it('calls the given onChange callback with the current selected index and value', () => {});

Now it’s the tricky part: implementing the tests in a way that it’s not coupled with the component’s implementation. 

This is important because we want to be able to refactor our code in ways that better suit the implementation needs without having to modify any of its tests. Attention: if the public API changes, that’s not a refactor! Code refactoring is the process of restructuring existing computer code without changing its external behavior.

You may ask yourself, “What is knowing implementation details?”. If the test code looks for an internal id or CSS class, is it an implementation detail? How about looking for a dependent component? Maybe a function from a 3rd party library? If the test knows one private implementation detail, does it mean that it can use any other private implementation detail as well?

To be honest, I don’t have a definitive answer to this dilemma. There are as many answers as there are development teams out there. And there’s no correct answer, only trade-offs. Mine, which gives me confidence in my code, is as follows.

We want to test the functionality of <SingleSelectionListGroup> component and we know that it must render according to Bootstrap’s style, therefore, it will use <ListGroup> and <ListGroupItem>. But the rendering part is just a detail for the new component. It doesn’t care about HTML tags or CSS classes. We just need to test that the render components are used correctly to represent the state and behavior.

Let’s do a quick thought exercise. Imagine that we want to know as little as possible about the rendering details. One way to achieve this is to incorporate the “end-user point of view”. This means writing tests that rely only on the artifacts that end up in the user’s browser/client like text labels and markup. We could test a bunch of features with these artifacts since most of them are possible to know or mock in the test.

There’s a particular caveat in the list item selection case. In order to test it, it is required to look for the active CSS class. But this class is a rendering detail that is the responsibility of the <ListGroupItem> component. Putting it in another way, the tests would know the details of the details.

Some teams argue that “the tests don’t care how active CSS class got rendered as long as it’s there.” And that works too. The main disadvantage is that if <ListGroupItem> changes class name from active to selected, <SingleSelectionListGroupItem> tests would fail for no reason. It’s a change totally unrelated to the component being tested so the tests should not break.

To me, the approach that gives the most confidence is testing that <SingleSelectionListGroup> uses <ListGroup> and <ListGroupItem> correctly, passing the right props. Yes, the test will know some implementation details but it won’t know the details of its internal components. This approach also protects <SingleSelectionListGroup>‘s tests from any changes internal to <ListGroup>and <ListGroupItem>.

More on this topic later. Here’s a test implementation that follows our guidelines. Red:

// src/components/listGroup.spec.js
describe("<SingleSelectionListGroup />", () => {
  it("renders according to specification", () => {
    const wrapper = shallow(
        <ListGroupItem>Item 1</ListGroupItem>
        <ListGroupItem>Item 2</ListGroupItem>

    const listGroup = wrapper.find(ListGroup);

  describe("and when an item is clicked", () => {
    describe("and it is NOT selected", () => {
      it("selects the clicked item", () => {
        const wrapper = shallow(
            <ListGroupItem>Item 1</ListGroupItem>
            <ListGroupItem>Item 2</ListGroupItem>


        ).toHaveProp("active", true);

      it("deselects any other selected item - single selection", () => {
        const wrapper = shallow(
            <ListGroupItem active>Item 1</ListGroupItem>
            <ListGroupItem>Item 2</ListGroupItem>

        ).toHaveProp("active", true);


        ).toHaveProp("active", false);

        ).toHaveProp("active", true);

    describe("and it IS selected", () => {
      it("deselects the clicked item", () => {
        const wrapper = shallow(
            <ListGroupItem>Item 1</ListGroupItem>
            <ListGroupItem active>Item 2</ListGroupItem>

        ).toHaveProp("active", true);


        ).toHaveProp("active", false);

        ).toHaveProp("active", false);

    it("calls the given onChange callback with the current selected index and value", () => {
      const changeSpy = jest.fn();
      const wrapper = shallow(
        <SingleSelectionListGroup onChange={changeSpy}>
          <ListGroupItem>Item 1</ListGroupItem>
          <ListGroupItem>Item 2</ListGroupItem>


        index: 0,
        value: "Item 1",


        index: -1,
        value: null,

Notice how the test above never looks for HTML specific details like tags or CSS classes. Those details are for the render components. The new tests only care about what the component really is supposed to do: handle the selection, user interactions and use the propper render components correctly.

Also notice that the tests only used shallow rendering! That’s the utility tool for isolating the component rendering. This forces the implementation to be very flat which is fine for the current needs. Granted, if the component structure was more complex we would need to use Enzyme’s dive() as well in the tests which are also implementation details.

Now go ahead and make all tests turn green. It’s a pretty cool challenge. You can check my solution on GitHub. Don’t forget to add a new Storybook story with the new component to see it in action.

This is it for today’s entry! I hope the confidence in your code has increased a little bit more with my explanations.

Until next time when, hopefully, this series will end.

Flattr this!

Confident React App – Part 4

Welcome to the continuation of the Confident React App blog post series. We’ve covered some considerable ground so take your time reading the series (part 1 | part 2 | part 3).

In this post, we’ll add a tool to our arsenal for testing components in the browser without much hassle: Storybook.

Telling component stories

We already used some important tools and techniques to our code base to increase our confidence:

  • Automated tests
  • Static type checking
  • Behavior Driven Development

But can you spot what’s missing so far? Well, it’s the application running in a browser, just like the end-user will. A dummy app for testing the components would be fairly easy to create but there a few downsides for this approach:

  • The real app depends on external APIs/resources so it’s slower.
  • It could be impossible to test some features due to the unavailability of the external APIs/resources.
  • The app code is more complex since it integrates many parts which makes it hard to verify components in isolation.
  • Apps can have many complex states which makes it hard to verify all use cases, especially error states.
  • It’s harder to iterate fast in the UI when there are too many dependencies.

A common way to avoid the pitfalls above is to create a separate app for the purpose of showcasing components and app states in a more structured and isolated way. Enter Storybook: the tool of choice for the question at hand. Storybook is quite powerful and versatile so I recommend reading through its examples and documentation. Let’s add it to our project:

npx -p @storybook/cli sb init

yarn flow-typed install @storybook/[email protected] @storybook/[email protected]

If everything goes well after the long install, there will be a bunch of new files in our project. Storybook is also already running with some demo content.

Storybook uses an original language for its API: you are supposed to showcase the features of your application in stories by module. For example, we want to showcase the <ListGroup> component so a story is added for it with “chapters” that show all it can do.

Edit the file src/stories/index.js and add the following code:

// @flow

import React from 'react';
import { storiesOf } from '@storybook/react';
import { ListGroup, ListGroupItem } from '../components/listGroup';

storiesOf('ListGroup', module)
.add('with items', () => (
    <ListGroupItem>item 1</ListGroupItem>
    <ListGroupItem>item 2</ListGroupItem>

Now, if you go to http://localhost:9009/?path=/story/listgroup–with-items, you can actually see and try for the first time the component!

… And it sucks. Even though the generated HTML is perfectly valid, it doesn’t look at all to the Bootstrap version:

This is exactly why we always need to test the application, or parts of it, in the browser; even with all the tools and techniques added so far, we’re still very far from the desired outcome.

You gotta have style

We’ve been talking a lot about Bootstrap and even implemented some code that relies on it, but we never added it as a dependency to our project.

There are many ways of fulfilling this step. For simplicity, we’re adding Bootstrap as a runtime dependency so only its production CSS is loaded by the page. To do so, we have to add custom tags to Storybook. Create the file .storybook/preview-head.html and add this:

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Bootstrap’s CSS will be loaded from a CDN inside of Storybook. Just restart Storybook and profit!

Enriching the leaves

OK, we have a very simple list of items but there are still two important functionalities missing:

  1. Active list items.
  2. Clickable items so that they are interactive.

Let’s jump straight into the red test:

// src/components/listGroup.spec.js

it('renders active when active prop is truthy', () => {
  const wrapper = shallow(<ListGroupItem active>item 1</ListGroupItem>);


And implement it to get a green test:

// src/components/listGroup.js

type ListGroupItemProps = {
  children: string,
  active?: boolean

export function ListGroupItem (props: ListGroupItemProps) {
  const classes = "list-group-item" + ( ? " active" : "")
  return <li className={classes}>{props.children}</li>;

Finally, a new story needs to be added so we can see the final result:

// src/stories/index.js

.add('with active items', () => (
    <ListGroupItem active>item 1</ListGroupItem>
    <ListGroupItem active>item 2</ListGroupItem>

For the clicking, the specification defines two options: either an &lt;a&gt; or &lt;button&gt;. Since we don’t need page navigation yet, the &lt;button&gt; is the right choice. Also, whenever an item is clicked, it must execute the given callback if any. The red tests:

// src/components/listGroup.spec.js

describe('when onClick prop is defined', () => {
  it('renders as an action button', () => {
    const wrapper = shallow(
      <ListGroupItem onClick={() => {}}>
        item 1

  it('renders as an active action button when active prop is truthy', () => {
    const wrapper = shallow(
      <ListGroupItem active onClick={() => {}}>
        item 1

  it('calls the given callback when clicked', () => {
    const onClickSpy = jest.fn();
    const wrapper = shallow(
      <ListGroupItem onClick={onClickSpy}>item 1</ListGroupItem>



To make the tests pass/green:

// src/components/listGroup.js
type ListGroupItemProps = {
  children: string,
  active?: boolean,
  onClick?: Function

export function ListGroupItem (props: ListGroupItemProps) {
  let classes = "list-group-item" + ( ? " active" : "");

  if(props.onClick) {
    classes += " list-group-item-action";
    return (
      <button type="button" className={classes} onClick={props.onClick}>  
  } else {
    return <li className={classes}>{props.children}</li>;

The last step is to verify it in the browser with a story:

// src/stories/index.js

import { action } from '@storybook/addon-actions';

.add('with actionable items', () => (
    <ListGroupItem active onClick={action("Item 1 clicked!")}>
      action item 1
    <ListGroupItem onClick={action("Item 2 clicked!")}>
      action item 2

There you go: our React implementation of the Bootstrap’s list group component is finally complete!

But what do we do with it? The answer lies in the app’s requirements: selecting an item when it’s clicked, multiple or single selections, deselecting…

In the next post, we’ll implement the behavior with some state and do a deeper discussion on how to test components in a way that makes us confident.


Flattr this!

Confident React App – Part 3

This is the third post on the series about Confident React App where I show how I build up confidence in the source code of my React apps. Here’s the beginning of the story.

In this post, we’ll finally start coding some React components but following some vital rules that will help us make reliable code.

Coding confidently with BDD + TDD

Research has shown that Test Driven Development is one of the most effective measures for increasing the perceived quality of the developed software: from ~40% to ~80% increase. They also measured the increase in effort/cost for applying it.

We can’t skip such an effective technique, right? But how do we do it? Well, there’s the TDD bible to study and also
“The Three Laws of TDD” to follow:

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.
  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

That’s much easier said than done. After months of practice, it still takes me a while to get into the TDD flow so I need to be very aware to not break the rules. Because of the accrued learning curve and effort, it’s easy to make mistakes and misuse it which causes some resentment. The most common issue I observe is test code that is too coupled with implementation details, especially in React apps.

I suspect that this happens because of the mindset the developer is in when doing tests first: you get framed on testing everything! However, 100% test coverage is counterproductive since not every part of your code is equally worth the test hassle and it’s also an illusion.

The Behavior Driven Development approach is my favorite because it sets the best mindset: it builds on top of TDD focusing on business/user goals and drive towards shared understanding through conversations. In other words, it’s a high-level spec that fosters communication. When we read the test cases out loud, it feels like normal speech so it fits snugly into our minds. Good software is software that fits in our heads, which is easier and faster to create good mental models about it.

Our acceptance criteria are already written in BDD style, so the devs – we – have a perfect guide to start with.

Starting from the bottom

For this particular case, I think starting from the bottom/leave components will be easier since it’s basically the list-group component from Bootstrap. We won’t need to implement all the described features – but make sure to get familiar with it.

We quickly realize that list-group is composed of multiple list-group-item‘s. A list of items! So the leaf component should be &lt;ListGroupItem&gt;. Since the two are closely related, let’s keep their implementation in the same file.

So we create the two files and fire up the tests:

mkdir src/components
touch src/components/listGroup.js
touch src/components/listGroup.spec.js

Don’t forget to add // @flow.

I’ve picked Airbnb’s Enzyme test renderer because it has the necessary functionality for writing the kind of tests I prefer the most. Notably, Enzyme’s got a few pitfalls to be avoided. I’ll explain why I still use shallow soon enough.

To add the tools we need:

yarn add -D enzyme enzyme-adapter-react-16 jest-enzyme && yarn flow-typed install [email protected]

And add the new file src/setupTests.js:

// @flow
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-enzyme';

configure({ adapter: new Adapter() });

A Component’s purpose

We start by describing what we’re testing: the new &lt;ListGroupItem /&gt; component. Its sole purpose is to return valid JSX, compliant with the component contract. The HTML + CSS defined by our external dependency, Bootstrap, is the contract that our React component must fulfill. It should be fairly simple to test because our component is just a pure function.

For now, Enzyme’s shallow is the right tool for the job.

// src/components/listGroup.spec.js
// @flow
import React from 'react';
import { shallow } from 'enzyme';
import ListGroupItem from './ListGroup';

describe('<ListGroupItem />', () => {
  it('renders according to specification', () => {
    shallow(<ListGroupItem />)

When we run the test watcher…

yarn test

… we get our first expected red of the cycle! This is obvious since there is no implementation yet. Keeping in mind the first rule of TDD, we implement our component to make this test pass:

// src/components/listGroup.js
// @flow
import React from 'react';

function ListGroupItem () {
  return null

export ListGroupItem;

Now we’re in the first expected green! Doesn’t that feel good? Let’s restart the cycle and get into red again by testing something more useful. The next step is to validate the generated structure. Red:

// src/components/listGroup.spec.js
it('renders according to specification', () => {
    shallow(<ListGroupItem />)

The test code above takes advantage of the cool matchers from jest-enzyme to make our code more readable. To make it green, the implementation must return the proper markup:

// src/components/listGroup.js
function ListGroupItem () {
  return <li className='list-group-item' />

The specification determines that every list item can have a string or an anchor as children. Let’s start with the string and assume it’s required. Red:

// src/components/listGroup.spec.js
describe('<ListGroupItem />', () => {
  it('renders according to specification', () => {
    const wrapper = shallow(<ListGroupItem>item 1</ListGroupItem>);

    expect(wrapper).toHaveText('item 1');

The implementation is more interesting now: in order to guarantee that the component is used correctly, we have to validate the given props. Flow comes in handy for this task. Green:

type ListGroupItemProps = {
  children: string,

function ListGroupItem (props: ListGroupItemProps) {
  return <li className="list-group-item">{props.children}</li>;

Note that the Jest watcher does not run Flow on file changes so type errors won’t break the tests. You can use flow-watch so Flow runs in every file change. Or, if you’re using an IDE, adding a Flow extension will come in handy.

This is enough features for this component for now. Let’s move on to the next component.

Red, Green, Red, Green, …

&lt;ListGroup&gt; is the parent component that has many &lt;ListGroupItem&gt;s. Just to save some time, here’s the whole component red tests:

describe('<ListGroup />', () => {
  it('renders according to specification', () => {
    const wrapper = shallow(
        <ListGroupItem>item 1</ListGroupItem>
        <ListGroupItem>item 2</ListGroupItem>


Now we have to put both components working together and since an empty list item didn’t make sense, a list group without list items doesn’t either. Green:

// src/components/listGroup.js
type ListGroupProps = {
  children: React.ChildrenArray<React.Element<typeof ListGroupItem>>

export function ListGroup (props: ListGroupProps) {
  return <ul className='list-group'>{props.children}</ul>

In the shallows, shallows…

shallow rendering is a powerful tool and having its documentation close by is quite handy. Never using it is a missed opportunity. Facebook has some more insights about it. Here are some reasons why I believe it’s the right tool for the component tests above:

  1. The components are just pure functions, no interactions with real DOM or higher-order components.
  2. Unit tests should be fast and shallow is faster than mount and render.
  3. Unit tests should be isolated. For &lt;ListGroupItem&gt; it’s easy because it’s completely independent but &lt;ListGroup&gt; depends on &lt;ListGroupItem&gt; as defined by the children argument type. Using mount/render would break the isolation of the component test because it renders the children.

Facebook’s react-dom/test-utils and react-test-renderer are testing libraries used by Enzyme. Which means that all the render stack from our test environment is mocked. The final result can be fully validated only when the code runs in a web browser. We’ll add another tool for validating components on the browser in another post.

Phew! What a ride. Thanks for reading all the way here. I really appreciate it. The series is not over though: the feature is far from done and the “leave components” are not completed yet.

Stay tuned for the next post in the series.

P.S.: All together now! In the shallow, shallow…

Flattr this!

Confident React App – Part 2

This is the second post in the series where I show how I build up the confidence in the source code of my React apps. Please read the first post before continuing.

Communications is the key

A study of public GitHub issues found out that 78% of all software bugs are caused by specification error. Take a moment to let that sink in… That’s a big percentage! Basically, the quality of your team’s communication skills is by far the best investment you can do in order to reduce bugs in any application. The same research shows that type checking, either with Flow or TypeScript account only for ~15% of bug prevention.

So make sure your team/organization strive for creating and fostering a culture of safe and effective communication. People should communicate using a ubiquitous language which helps clarify specific jargons, contexts, and symbols. Not to mention that even improving formal language skills can have a positive impact. There’s nothing more powerful than a person who’s articulated and can think and speak.

Also the tools for communication should not be neglected. Wiki, Slack, whiteboards, Jira, Post-its, sharpies, company phones, video conference rooms and what-not are means to an important end.

Understanding the feature

We would like to quickly see the GitHub issues reported in our enterprise software in an integrated fashion so that we can find the necessary information fast; without switching context.

Our Customers

To achieve the desires of our customers, our (imaginary) multi-disciplinary development team has done research and a lot of discussions. Afterward, we came up with the following acceptance criteria written in our own syntax/DSL:

* Github integration *
  When the user is in the issues screen
    it must show a loading indicator while repo data is being fetched
    and repo data is available
      it must show a list of repos names
      it must show a summary of all open issues
      and there are open issues in a repo
        it must show the count of opened issues next to the repo name
      and when a repo is clicked
        and it is NOT selected
          it selects the clicked item
          and there ARE open repo issues
            it replaces the summary with the list of open repo issues
          and there ARE NOT open repo issues
            it shows the no issues message
        and it IS selected
          it deselects the clicked item
          it replaces the list of open repo issues with the summary

The trick for reading the above is that indentation must be taken into account. All sentences are appended to its parent group. Sentences on the same level of indentation are not appended. The sentences usually start with setting some pre-conditions (e.g.: data is available) or user behavior (e.g.: clicking an item) and they finish with some sort of outcome/side effect. (e.g.: selects the clicked item).

Here’s a complete example:
When the user is in the issues screen and repo data is available and a repo is clicked and it is NOT selected it selects the clicked item.

It is a bit weird at first but our team likes it and it works for us. Gherkin is a very popular choice if you don’t want to roll your own DSL.

Component specification

Our designers opted for using Twitter Bootstrap as the base of the app GUI and for the feature we’ll need the List Group component. The component’s documentation serves as specs and acceptance criteria for the React implementation that we’ll provide.

One of the variations of Bootstrap’s list-group component

So go back and read the acceptance criteria for the feature and the List Group specification. Try to imagine more use case scenarios or edge cases. Can you rewrite the sentences in a more clear way? Have you spoted an important missing thing?

In the next post we’ll dive into coding, I promise. But it will come with a twist.


Flattr this!

Confident React App – Part I

Kent C. Dodds has written one of the coolest pieces about software testing that I’ve read recently. It’s a great overview of the most common types of testing. The “CONFIDENCE you must have in the code you deliver” is an original light that he shines on the topic. Before you continue reading this, go read his article first. It’s well worth it!

OK, do you feel inspired too? Then let me explain and show you how I make my React codebases reliable and my confidence levels pretty high.

First step is to create our React app. I’ll use Create React App (CRA) since it’s super simple and still very popular.

npx create-react-app confident-react-app

Let’s start by fulfilling the base of Kent’s Testing Trophy requirements. For that we use a bunch of tools that will save us from most of trivial JS mistakes.


CRA uses ESLint by default which is great. From ESLint’s website: “JavaScript, being a dynamic and loosely-typed language, is especially prone to developer error. Without the benefit of a compilation process, JavaScript code is typically executed in order to find syntax or other errors. Linting tools like ESLint allow developers to discover problems with their JavaScript code without executing it.” And here’s the exact ESLint configuration used by CRA. You can see that the configuration also applies accessibility linting rules which is a really nice bonus. It helps us create code that respects some of the impaired internet users.

Static type checking

JS is a dynamic language and experienced developers can really take advantage of dynamic types and objects. But even experienced developers make silly mistakes, work with other less experienced devs and most of a JS codebase relies on static types anyway. So a codebase that uses a strong type system can benefit from detecting type error mistakes quite early. Facebook created and uses Flow, a static type checker for javascript.

OK, Flow is intrusive. In order to benefit from it, your code will look quite similar to TypeScript. To be honest, if you’re doing a small library/app and even working with other developers with limited experience, adopting Flow/TypeScript will probably not be worth it due to the added entropy. It’s a part of the nature of being a JS developer, you get burned many times until you finally learn and embrace. I personally got so used to it that most of the times I find super annoying to write so much type boilerplate.

Which one should you choose? That’s an ever going debate that I don’t know the answer to. I recommend that you try both and get the feeling for yourself. This kind of choice is just too hard to be impartial to take.

For this series of posts, lets assume we’re building an enterprise multi-national application in a team with dozens of developers spread across the globe. We’ll take Flow to the next level by using it in strict mode. From now on, every JS file must have // @flow in its first line, even tests.

yarn add flow-bin &amp;&amp; yarn flow init

If you run the flow command it should report errors on the tests since it doesn’t recognize Jest’s global functions – itdescribe, etc. To fix this you must inform Flow that Jest is a library with all its interface definitions. Thankfully there’s flow-typed which is a tool for installing community-supported library interface definitions.

yarn add -D flow-typed &amp;&amp; yarn run flow-typed install [email protected]

Unfortunately these tools do not run by default with CRA’s own scripts. Let’s validate our code for every action, so this how we setup the scripts in our package.json:

"scripts": {
    "start": "yarn validate &amp;&amp; react-scripts start",
    "build": "yarn validate &amp;&amp; react-scripts build",
    "test": "yarn validate &amp;&amp; react-scripts test",
    "validate": "yarn lint &amp;&amp; yarn flow",
    "lint": "eslint src/**/*.js",
    "flow": "flow",
    "flow-typed": "flow-typed"

Phew! A lot of setup and we haven’t written any line of code yet. We deserve a break. Building up the confidence in your codebase is not so simple and can be hard to build – just like in real life – but the return on the investment will be worth it.

You can find the source code on Github.

Next post we’ll talk about what we’ll be building and how.


Flattr this!

Flexing the Flexbox muscle

In order to better understand CSS Flexbox let us build our own
basic Grid system. It’s also a good chance to practice separation of CSS code for layout and from styling. When the layout is separated from style, the code becomes less repetitive, easier to compose and reuse. But by no means what we’re doing here is production ready! This is just a small learning exercise. You’re invited to come learn with me.

All grid frameworks out there have their own rules, some kind of API, that is different from each other. Each library has
its own flavor which is natural since everyone has different ways to solve the same problem. You should experiment with a few and see which one you like the most. Our approach is very basic but will be enough for our goals. Let’s define our rules:

  1. No JavaScript
  2. The grid is delimited by a root element. All our classes and markup only work inside of it.
  3. There are only Rows and Columns.
  4. The grid can have Rows. Rows can have Columns. Columns can have Rows.
  5. Rows always take the full available width of its parent container.
  6. Columns share the whole available width of the Row if no size is specified. They shrink and grow as necessary. They only break/wrap if there’s no available space.

We start off the first use case: 2 rows that take the full-width, each with 3 columns that share equally the width available. Let’s write the markup first:

[pastacode lang=”markup” manual=”%3Cdiv%20class%3D%22flex-grid%22%3E%0A%20%20%3Cdiv%20class%3D%22row%22%3E%0A%20%20%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%20%20%3Ch1%3ERow%201%20Column%201%3C%2Fh1%3E%0A%20%20%20%20%3C%2Fdiv%3E%0A%20%20%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%20%20%3Ch1%3ERow%201%20Column%202%3C%2Fh1%3E%0A%20%20%20%20%3C%2Fdiv%3E%0A%20%20%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%20%20%3Ch1%3ERow%201%20Column%203%3C%2Fh1%3E%0A%20%20%20%20%3C%2Fdiv%3E%0A%20%20%3C%2Fdiv%3E%0A%20%20%3Cdiv%20class%3D%22row%22%3E%0A%20%20%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%20%20%3Ch1%3ERow%202%20Column%201%3C%2Fh1%3E%0A%20%20%20%20%3C%2Fdiv%3E%0A%20%20%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%20%20%3Ch1%3ERow%202%20Column%202%3C%2Fh1%3E%0A%20%20%20%20%3C%2Fdiv%3E%0A%20%20%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%20%20%3Ch1%3ERow%202%20Column%203%3C%2Fh1%3E%0A%20%20%20%20%3C%2Fdiv%3E%0A%20%20%3C%2Fdiv%3E%0A%3C%2Fdiv%3E” message=”” highlight=”” provider=”manual”/]

Working with invisible elements is not that easy so let’s add some visual cues so we can track our progress. A few borders and background color will do the trick:

[pastacode lang=”css” manual=”.flex-grid%20%7B%0A%20%20background-color%3A%20%23ddd%3B%0A%7D%0A%0A.flex-grid%20.row%20%7B%0A%20%20border%3A%201px%20dotted%20red%3B%0A%20%20box-sizing%3A%20border-box%3B%0A%7D%0A%0A.flex-grid%20.row%20.col%20%7B%0A%20%20border%3A%201px%20dashed%20blue%3B%0A%20%20box-sizing%3A%20border-box%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

Time to turn on the Flexbox! Just add display: flex; to .flex-grid and Boom! The layout is totally wrecked now but we’ll adjust it step-by-step.

Since our grid can only have Rows as direct children, and every row must always be on top of each other, we have to add flex-direction: column; to .flex-grid. Wait, what!? Rows as columns?! Yep. Not very intuitive at first glance. That’s why this exercise is important: it will put us out of our comfort zone and force us to really grasp the theory and put it into practice.

So what’s going on here?

When we set the flex-direction to “column“, we’re telling that we want every direct child element of the flex container to be displayed on top of each other to form a column/stack. Which is what we want: rows stacked on top of each other occupying the whole width.

Unfortunately, the columns are behaving just like Rows too. We want that all columns of a row share the available width by default. This also means that the columns must appear next to each other, in a line. We could achieve this by setting display: inline; or float: left; to the columns … but that’s not Flexbox. Since the layout of the Columns is ruled by the parent container, setting display: flex; to .flex-grid .row does one of the tricks: Columns in a row. But now the Columns only occupy the space required by its contents. To fix this we must tell the Columns to grow as much as they can by setting flex: 1; to .flex-grid .row .col. Uh la la!

Things are starting to look good but let’s first try some nesting. Replace the contents of the first Column of the first Row with the following snippet.

[pastacode lang=”markup” manual=”%3Cdiv%20class%3D%22row%22%3E%0A%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%3Cspan%3EInner%20Row%201%20Col%201%3C%2Fspan%3E%0A%20%20%3C%2Fdiv%3E%0A%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%3Ch4%3EInner%20Row%201%20Col%202%3C%2Fh4%3E%0A%20%20%3C%2Fdiv%3E%0A%3C%2Fdiv%3E%0A%3Cdiv%20class%3D%22row%22%3E%0A%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%3Cp%3EInner%20Row%202%3C%2Fp%3E%0A%20%20%3C%2Fdiv%3E%0A%3C%2Fdiv%3E%0A%3Cdiv%20class%3D%22row%22%3E%0A%20%20%3Cdiv%20class%3D%22col%22%3E%0A%20%20%20%20%3Cspan%3EInner%20Row%203%3C%2Fspan%3E%0A%20%20%3C%2Fdiv%3E%0A%3C%2Fdiv%3E” message=”” highlight=”” provider=”manual”/]

Beautiful, it works wonders out of the box! This truly shows the potential of Flexbox. Let’s try to add some width modifier to our columns so we can have so more control over our layouts. We’ll skip responsive breakpoints for now and apply the widths for all sizes:

  • .all-20: 1/5 (20%)
  • .all-25: 1/4 (25%)
  • .all-33: 1/3 (33%)
  • .all-50: 1/2 (50%)
  • .all-60: 3/5 (60%)
  • .all-66: 2/3 (66%)
  • .all-75: 3/4 (75%)

Another important detail: when we specify the column width, that’s the min and max width it should have -a fixed proportion. So we add the following selectors and rules:

[pastacode lang=”css” manual=”.flex-grid%20.row%20.col.all-20%20%7B%0A%20%20max-width%3A%2020%25%3B%0A%20%20width%3A%2020%25%3B%0A%7D%0A%0A.flex-grid%20.row%20.col.all-25%20%7B%0A%20%20max-width%3A%2025%25%3B%0A%20%20width%3A%2025%25%3B%0A%7D%0A%0A.flex-grid%20.row%20.col.all-33%20%7B%0A%20%20max-width%3A%2033%25%3B%0A%20%20width%3A%2033%25%3B%0A%7D%0A%0A.flex-grid%20.row%20.col.all-50%20%7B%0A%20%20max-width%3A%2050%25%3B%0A%20%20width%3A%2050%25%3B%0A%7D%0A%0A.flex-grid%20.row%20.col.all-60%20%7B%0A%20%20max-width%3A%2060%25%3B%0A%20%20width%3A%2060%25%3B%0A%7D%0A%0A.flex-grid%20.row%20.col.all-66%20%7B%0A%20%20max-width%3A%2066%25%3B%0A%20%20width%3A%2066%25%3B%0A%7D%0A%0A.flex-grid%20.row%20.col.all-75%20%7B%0A%20%20max-width%3A%2075%25%3B%0A%20%20width%3A%2075%25%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

So if we add .all-25 to Column 2 of Row 1, it shrinks to 1/4 of the Row width as expected and the other two Columns grow. But if instead of .all-25 we apply .all-75 it doesn’t work, they all occupy 1/3 of the width. This is a bit trickier.

When we set flex: 1; it’s actually a short-hand for setting flex-grow: 1; flex-shrink: 1; flex-basis: 0%; The most important detail being flex-basis: 0%;. This means that the element will not enforce its min size. And since all other Columns have the same rule, the result is that they only grow to the max width which is equally divided. To make sure the Column has the width it was supposed to have, we got to set flex-basis: 100%; to all width modifiers. And now it’s working!

But what happens when we apply .all-25 to Column 1 of Row 1? The first two Columns (1/4 + 3/4 = 1) should occupy 100% of the Row’s width but why the hell Column 3 is still in the same Row?! Why didn’t it break to the second line? Well, that’s because we didn’t tell the Row to allow it. And to do it we must set flex-wrap: wrap; to .flex-grid .row.

Another interesting feature we can add to our Flexbox grid system is the ability to align Columns. And who controls the alignment? The parent container: Row! We can create the following modifier with the Flexbox property justify-content to put Columns at the horizontal center of the Row:

[pastacode lang=”css” manual=”.flex-grid%20.row.hor-center%20%7B%0A%20%20justify-content%3A%20center%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

It’s important to note that this only works if the Columns have a defined width. How can you know what’s the center of the Row if the Column is occupying the whole width? Once the Column has a width, say 50%, the Row can calculate how much space is left and position the Column at its horizontal center.

But you want to put the Columns at the vertical center of the Row, right? For that, we need a different Flexbox prop: align-items. If justify-content works by placing elements on the X/horizontal axis, align-items works on the Y/vertical axis. So we add a new Row modifier to center columns vertically:

[pastacode lang=”css” manual=”.flex-grid%20.row.vert-center%20%7B%0A%20%20align-items%3A%20center%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

There you go! A super basic base for a grid system implemented with Flexbox. Just enough features so we can practice some core concepts and solidify them in our CSS knowledge base.

The whole CSS for our basic Flexbox grid system:

[pastacode lang=”css” manual=”.flex-grid%20%7B%0A%20%20%20background-color%3A%20%23ddd%3B%0A%20%20%20display%3A%20flex%3B%0A%20%20%20flex-direction%3A%20column%3B%0A%20%7D%0A%0A.flex-grid%20.row%20%7B%0A%20%20%20border%3A%201px%20dotted%20red%3B%0A%20%20%20box-sizing%3A%20border-box%3B%0A%20%20%20display%3A%20flex%3B%0A%20%20%20flex-wrap%3A%20wrap%3B%0A%20%7D%0A%0A.flex-grid%20.row.hor-center%20%7B%0A%20%20justify-content%3A%20center%3B%0A%7D%0A%0A.flex-grid%20.row.vert-center%20%7B%0A%20%20align-items%3A%20center%3B%0A%7D%0A%0A.flex-grid%20.row%20.col%20%7B%0A%20%20%20border%3A%201px%20dashed%20blue%3B%0A%20%20%20box-sizing%3A%20border-box%3B%0A%20%20%20flex%3A%201%3B%0A%20%20%20padding-right%3A%20.5em%3B%0A%20%7D%0A%0A.flex-grid%20.row%20.col%3Alast-child%20%7B%0A%20%20%20padding-right%3A%200%3B%0A%20%7D%0A%0A.flex-grid%20.row%20.col.all-20%20%7B%0A%20%20%20flex-basis%3A%20100%25%3B%0A%20%20%20max-width%3A%2020%25%3B%0A%20%20%20width%3A%2020%25%3B%0A%20%7D%0A%0A.flex-grid%20.row%20.col.all-25%20%7B%0A%20%20%20flex-basis%3A%20100%25%3B%0A%20%20%20max-width%3A%2025%25%3B%0A%20%20%20width%3A%2025%25%3B%0A%20%7D%0A%0A.flex-grid%20.row%20.col.all-33%20%7B%0A%20%20%20flex-basis%3A%20100%25%3B%0A%20%20%20max-width%3A%2033%25%3B%0A%20%20%20width%3A%2033%25%3B%0A%20%7D%0A%0A.flex-grid%20.row%20.col.all-50%20%7B%0A%20%20%20flex-basis%3A%20100%25%3B%0A%20%20%20max-width%3A%2050%25%3B%0A%20%20%20width%3A%2050%25%3B%0A%20%7D%0A%0A.flex-grid%20.row%20.col.all-60%20%7B%0A%20%20%20flex-basis%3A%20100%25%3B%0A%20%20%20max-width%3A%2060%25%3B%0A%20%20%20width%3A%2060%25%3B%0A%20%7D%0A%0A.flex-grid%20.row%20.col.all-66%20%7B%0A%20%20%20flex-basis%3A%20100%25%3B%0A%20%20%20max-width%3A%2066%25%3B%0A%20%20%20width%3A%2066%25%3B%0A%20%7D%0A%0A.flex-grid%20.row%20.col.all-75%20%7B%0A%20%20%20flex-basis%3A%20100%25%3B%0A%20%20%20max-width%3A%2075%25%3B%0A%20%20%20width%3A%2075%25%3B%0A%20%7D%0A” message=”” highlight=”” provider=”manual”/]

This is a very limited implementation and we can still achieve some interesting results:

Keep on honing your skills while having some fun.

Flattr this!

Prefix Sums – Alternative explanation to Codility’s


Hello there fellow coder!

This is my explanation of “Prefix Sums” a powerful and versatile algorithm technique.
It can be used for optimizations, parallelization or enabling other algorithms that are essential for all kinds of complex problems.
So it’s a very useful concept to understand, to know where and how to use it. For this post you better be familiar with Big O notation  as I use it to talk about time complexity.

My other motivation was Codility’s material on the subject and how confusing it is. Hopefully my explanation will be clearer than theirs. My code examples are all in JavaScript so you can test it right in your browser.

The concept

Trust me, it’s much easier than it sounds: given a list of numbers A, create a new list P of numbers on which each element is the sum of all the numbers from A prior to its index.

If you are a visual person, this is what it is (A is input and P is the output):

Prefix Sum - P of A
A diagram showing how the Prefix Sum algorithm technique works. P[1] = P[0] + A[1] = 2 + 3 = 5.
If you are a mathematical person, this is what it is:
 Given A = [a<sub>0</sub>, a<sub>1</sub>, a<sub>2</sub>, ... , a<sub>n-1</sub>], of size <i>n &gt; 0</i>
Prefix Sums is
 P = [a<sub>0</sub>, (a<sub>0</sub> + a<sub>1</sub>), (a<sub>0</sub>+a<sub>1</sub>+a<sub>2</sub>), ... , (a<sub>0</sub>+a<sub>1</sub>+ ... + a<sub>n-1</sub>)] 
Or in other words:
P[x] = P[x-1] + A[x]

Like I said, easy huh?

A JavaScript Implementation

There are many ways of implementing this technique but I like this one because is quite readable:

As you can see, its time complexity is linear, O(n). Now that the concept is clear, let’s use it.

Simple Example

Imagine that you have to calculate many many times the sum of parts of an array of numbers. It could be for displaying a heat map or the average stock price. Our example just calculates the sum of all sub-arrays/slices of 5 elements from an initial big array.

The most straight forward way to do it is by repeatedly do the iterative sum as many time as needed. Maybe like so:
The function sumArrayLinear(A, start, end) from the previous Gist can be represented as:
sumArrayLinear(A,x,y): A<sub>x</sub> + A<sub>x+1</sub> + ... A<sub>y-1</sub> + A<sub>y</sub>
And we can apply it like so:
sumArrayLinear([2,3,7,5],1,3): A<sub>1</sub> + A<sub>2</sub> + A<sub>3</sub> = 3 + 7 + 5 = 15
The time complexity of our example is O(n x m). Which is not bad.

But now you have another tool available for your disposal: Prefix Sums.

Let’s put it to use.
We calculate the Prefix Sums array with the numbers array. Then we define a new function which takes the Prefix Sums array as follows:
sumPrefixSumArray(P,x,y): P<sub>y</sub> - P<sub>x-1</sub>
Which basically reads as: The sum of the interval is the sum at the end (y) minus the sum of everything before the start of the interval (x-1). So with just one operation we obtain the result. Its time complexity is constant, O(1). Let’s try with our example.

The Prefix Sum of A = [2,3,7,5] is P = [2,5,12,17] .
sumPrefixSumArray(P,1,3): P<sub>3</sub> - P<sub>1-1</sub> = 17 - 2 = 15
Which is the same result as before, therefore:
A<sub>x</sub> + A<sub>x+1</sub> + ... + A<sub>y-1</sub> + A<sub>y</sub> = P<sub>y</sub> - P<sub>x-1</sub>

We can rewrite our code to use our new function:

The total time complexity is O(n) + m x O(1) which is simply O(n+m). And that’s pretty good! Of course, it all depends on the values of m & n. For our example, the first approach needs roughly 140 operations to obtain the resulting array while the seconds needs only 61.


There you have it!
The Prefix Sums technique for all sorts of other more complex problems. A powerful simple idea.
Was I clear? Spotted any problems or bugs? Do you know other examples where Prefix Sums can be used? Speak up on the comments bellow.


Flattr this!

Memoir: Send your Remember Notes to Microsoft OneNote™

Hello everybody,

Great news for us, BB10 loyal users: independent app development is not dead yet!

I have created a very simple app but which I think it’s really neat. It’s called “Memoir” and it is immensely useful to me and hopefully it will be for you too. It’s not free because I put a lot of effort in it and I value my time and effort. So, if you want more apps for BB10, please support your favorite independent dev by buying and reviewing our apps. With enough paying costumers it will enable me to continue doing what I like: cool and useful BB10 apps!

I’m giving my best with this app but even so there will be bugs. Actually, this is an unofficial BETA release. It works just fine in most cases but there are some edge cases that are not fully covered so … don’t push it too much. Or push it and break it but, please, report it to me so I can fix it.

This first version has only the core features but if reception is good, I’m planing to add more cool stuff. You can even ask for what would you like to see it doing. Just send me an email or a message in Twitter.

Grab your copy on BlackBerry World while it’s on LAUNCH SALE for 50% Off the regular price! Promo will end when I release the next version so hurry up before I release it.

Please share it with your friends and spread the word.

Get It At BlackBerry World

MEMOIR – Send your Remember Notes to Microsoft’s OneNote™

Memoir* [mem-wahr, -wawr]; noun;
1. A record of events written by a person having intimate knowledge of them and based on personal observation.
2. Usually, memoirs. An account of one’s personal life and experiences; autobiography.
The published record of the proceedings of a group or organization, as of a learned society.
3. A biography or biographical sketch.
Even tough BlackBerry provides a great note taking app, Remember, it has a big shortcoming: it’s impossible to backup its data or export it, not even with BlackBerry Link. This means that you have to manually copy and paste all data somewhere safe.

Don’t let your precious memories go to waste. With the Memoir app you can secure your memories in to the cloud with just one tap.

All the Notes and Folders stored on BB10’s Remember app can be easily uploaded to Microsoft™’s excellent OneNote™ note taking app/service. A Notebook named “BB10 Notes by Memoir” is created in your OneNote™/OneDrive™ account. Every Note Folder from Remember is a Section of the notebook. Every Note from Remember is a Page on OneNote™.

It’s a free cross-platform app and service. It’s has many advanced features and is deeply integrated with the latest version of Windows™ and their cloud storage service OneDrive™. It’s a perfect place for preserving your precious notes and enabling multiple ways of accessing it. To use Memoir you’ll need to have a Microsoft™ account.

– Support for Remember Notes and Folders.
– Attachments: images, audio, pdf, ppt, doc, xls e etc.
– Upload All with 1-Tap.
– Fast Native/Cascades interface. Very simple and effective.
– Secure integration with Microsoft™ Account. A Microsoft™ account is required. OneNote™ permissions must be granted.
– One-way synchronization. Only changes from Remember app are detected and uploaded.
– Support for OS 10.3.0 and higher.

– Integration with other cloud services. Google™ or EverNote™? You choose!
– Support for Tasks.
– Two-way synchronization. Changes to Notes made from OneNote™’s apps are downloaded to the device and appear on Remember app.
– Give OneNote™ permission only once. Permission is only granted for 1 hour in current version.
– Support for OS 10.2.1
– Other languages. Volunteer native speakers are welcome!
– Change OneNote™ Section by changing Notes Folder
– Change OneNote™ Master Notebook name

Ask for what feature you want most on the app review or by email: [email protected]

If you have any issues please contact our support email or reach me on Twitter.

Thanks for your time!

Here are some screenshots of the running on a Z10 and Q10:

Flattr this!

Why bother with BB10 development?

Yup, call me stubborn. What can I say besides that I really like the underdog, the odd, the beaten up and failed. My last post was about a project that I did in Flash and now a new post about a BlackBerry 10 app. Those are two technologies that I have very good experience and that I have a lot of fun using so on my free time I can’t help my self. What do I gain from it? What motivates me?

There’s something special about the underdogs: their despair to succeed. Much like the old saying about “Never fight a cornered animal for it will give a hell of a fight for it’s life”. A company that is in trouble will try their best to succeed – or at least they should. And what tech companies do best? They innovate! They put their best efforts into bringing great technologies hoping that it will win the market’s heart and save them. I find this situation greatly interesting so I watch closely their fight for life.

BlackBerry was – well, still is – cornered so they tried their best and as a result we have: BB10 OS and Blend on the software side and the Passport representing the hardware. Both extremely innovative products on their own merits but unfortunately they didn’t save the company. When innovation doesn’t work, companies put a fresh coat of paint on their best selling product and try to sell the hell out of it – the Classic – or they copy their competitors – the Priv with Android. Nowadays I don’t watch BlackBerry anymore… but let’s move on.

I do learn a lot about the problems at hand, like using the OneNote REST API, how to make multi-threaded programs, memory management, development of User Interface and Experience, localization, so on and so forth. These are actually the concepts that are the hardest to learn and master but the ones that I can pretty much take with me and use wherever needed. Just the implementation details will be different.

There’s a lot of value in mastering a programming language, framework or another tool. Many times I had to help a fellow senior developer on my team to deal with JavaScript craziness. Oh so many bugs on which the fix was some insane language detail that they didn’t know. I coined a phrase that I used multiple times on my code reviews: “JavaScript is a bitch”. So definitely yes, my expertise with Flash and Cascades – BlackBerry’s own native framework for app development based on Qt – won’t get me that broad advantage on the market place but there are still COBOL experts being hired right?

Another thing that I got used to was people frequently asking me, with an incredulous face, “Why BlackBerry?!”. There’s a strong reason and it’s quite reasonable. BlackBerry World has a little bit more than 370K apps available for download. iTunes App Store has more than 1.500K! That’s 4x times more apps, 4x more competitors. Barely any room for indie devs. There’s also lack of official support from popular services like Uber and Telegram. On BlackBerry World there’s only one very good paid app for each, a couple of odd balls.

These points show two clear things: as a costumer it sucks to have a BB10 phone because you’ll miss a lot of apps, a problem that for many experts was the crux of BlackBerry’s demise. As an independent developer it’s a gold mine! It’s all about competition and marketing power. With the same amount of effort I can have a very good compelling Sudoku game or Telegram app on BlackBerry 10 without much competition from other players. How can one indie dev compete with hundreds of other apps available on Apple’s AppStore, of which the best ones are the official ones or created by App Factories with dozens of dedicated professionals? My indie app would univocally end up in the middle of the “noise”, the sea of dead apps full of clones and ad-ware. And no matter how much I polish and improve my app it wouldn’t leave this dreadful app store deadzone. To leave it, the app must be heavily marketed! On forums, podcasts, tech blogs, forums, Twitter, Facebook and any other channel you can think of. But remember, your competitors can afford Super Bowl ads and hire Hollywood movie stars.

What’s for grabs? BlackBerry 10 has sold an estimated 15 million units world wide and shrinking. Apple has a whole f****** lot of millions and growing. The effort so sell 100K on BB10 is quite low and actually reasonable considering that if you have a unique essential app. A person will simply have to buy it from you because they are stuck with you. To sell 100k on the iTunes App Store you’ll have to invest much much more. Wanna be a billionaire? Be a CEO of a startup, get a lot of funding for development and marketing and go for Apple. Wanna be a millionaire, work hard and go for BlackBerry (while it lasts). As an indie dev, BB10 is just more reachable therefore much more motivating. Oh, and you can apply my arguments if you change Apple for Android and BB10 for Windows Phone.

I hope that the answer to my question was clear and if you are smart enough, you won’t bother with BB10. (And will let this small gold mine just for a few silly ones).


Flattr this!

Final Project on Learning – The 3 main things you need to know about Learning

Has anyone ever teach you how to learn? Strange question, right? I did the same puzzled expression but as I thought about it I came to an easy answer: no, nobody ever taught me how to learn. For me learning is almost like an instinct, something that we’re born with and that we can’t directly control such as breathing or sleeping. No need to worry about learning about it. So I was really intrigued when I saw the online course offered by University of California, San Diego called Learning How to Learn: Powerful mental tools to help you master tough subjects” by Dr. Barbara Oakley, Dr. Terrence Sejnowski. After checking out what it was all about I was convinced that it wouldn’t hurt to take the online classes. When I decided to enroll on the course I still didn’t know I was going to walk 120km and get married during the same period but I still managed to participate. And the course was quite cool! I indeed learned many things about learning so I’m here to teach you some of my favorite findings.

Two distinct modes of thinking

We rarely notice it but we do think in different ways in different situations. Researchers have found that we have two fundamentally different modes of thinking. The first time I encountered this concept was in 2013 when I read the best selling book “Thinking Fast & Slow” by Daniel Kahneman, a winner of the Nobel Prize in Economics. On Kahneman’s book, he calls it System 1 & System 2. On the course it’s called Diffuse and
Focused modes respectively. Barbara Oakley and Daniel Kahneman both talk about the same general concept but I prefer Daniel’s approach more. In this post I mash them together to get an even depper understanding.

The mind divided in two systems: fast and slow
The divided mind. Credit to: David Plunkert via NYT 11-27-11


When we have to manually multiply 2 big numbers we have to pay close attention to all the steps involved in the arithmetic operation, recall easier multiplication values, sum numbers and so forth. We do all that on the Focused mode of thinking, a.k.a. System 2. It is our slow, deliberate, analytical and consciously effortful mode of reasoning about the world. You can tell if a person is really engaged on this mode of thinking by observing their eyes: just note how dilated their pupils are. They call it Focused to give this sense of gathered organized thoughts.

But this mode has three big disadvantages: it requires a lot of energy, it gets tired and it is really lazy. And before we notice we already switched to another mode of thinking.


A.k.a. System 1, our fast, automatic, intuitive, creative and largely unconscious mode. It detects hostility in a voice and effortlessly completes the phrase “bread and. . . . ” or “2 + 2 = ?“. It’s so fast and so effortless that we use it most of the time and we usually do just fine with it, we even let it fool ourselves by it. And that’s great! Imagine if you had to worry and focus on every single banal activity or situation that you encounter in your life like deciding which hand to use to open a door when you have both hands free and perfectly fine. We would live in constant stress, depleting precious limited energy that could be used for more important tasks. So relying on the Diffused mode of thinking is more relaxing.

The course also teaches us another very important role that this mode of thinking has: making new brain cells connections that forms new creative ideas. It has happened to you and me many times: when we least expect it a crazy thought pops into our mind. Most of the time it’s something totally useless and silly like “What if popcorn grew on plants?” but sometimes it could lead to the birth of a new scientific discovery “Why should that apple always descend perpendicularly to the ground?“. This is the wonderful background workings of Diffused thinking, called that to give the sense of a more disorderly, spread out thoughts.

Visual representation of Systems 1 and 2 of Daniel Kahneman
Daniel Kahneman’s Systems in a nutshell. Credit to Eva-Lotta Lamm, 2011.

Knowing how differently both ways work is important so that we know when and how to use them. A big fallacy is to not use enough of Diffuse thinking and abuse Focused thinking. Just relax your mind and move your body for some minutes, this way you give time to your brain to recharge Focused Mode and use Diffuse Mode.


Now this is actually an answer for something that I wondered myself many times: why the heck do we sleep so much?! We’re so vulnerable and useless while sleeping and it’s such a waste of time considering the short lifespan that we humans have. It’s not like I’m a tortoise that can live for centuries! Alas, a good answer.

The mind is refreshed when we sleep
Credit to Jeff Iliff via TED “One more reason to get a good night’s sleep”

Brain’s waste cleanup scheme

When we’re awake, the brain produces toxins, byproducts of its own activities, which accumulate and degrade it’s functionality. Our mind becomes murky so it’s harder to concentrate, remember and construct rational thoughts. So it’s only when we sleep that the brain switches to cleaning mode: the brain cells shrink a little, a fluid called Cerebralspinal Fluid (CSF) flows through its cells, around all the blood vessels, removing all the toxins. The CSF then dumps the toxins into the blood stream. Our mind is now refreshed! This is a very elegant solution, unique to the brain. The rest of the body has the Lymphatic System, another set of vessels with fluids that runs throughout our bodies, that drains the byproducts of other organs. So it’s important to always have a good night’s sleep before an important test.

CSF flowing inside a rat's brain
CSF flowing inside a rat’s brain. Credit to Jeff Iliff via TED “One more reason to get a good night’s sleep”

In fact, getting too little sleep doesn’t just make you do worse on tests, too little sleep, over too long of a time, can also be associated with all sorts of nasty conditions. Avoid sleeping dreprivation at all costs!

Sleep to learn and understand

But sleep does more than just allow our brain to wash away toxins. It’s actually important part of the memory and learning process. It’s seems that during sleep our brain tidies up ideas and concepts we’re thinking about and learning. It erases the less important parts of memories and simultaneously strengthens areas that we want to remember. During sleep our brain also rehearses some
of the tougher parts of whatever we’re trying to learn, going over and over neural patterns to deepen and strengthen them.

Comparison of the CSF flow of a sleeping and awake rat's brain
Comparison of the CSF flow of a sleeping and awake rat’s brain. Credit to Jeff Iliff via TED “One more reason to get a good night’s sleep”

Sleep has also been shown to make a remarkable difference in our ability to figure out difficult problems and to understand what we’re trying to learn.
It’s as if the complete deactivation of the conscious you helps other areas of the brain start talking more easily to one another, allowing them to put together the neural solution to our learning task while we’re sleeping.

Of course, we must also plant the seed for our diffuse mode by first doing focused mode work. If we’re going over what we’re learning right before
going to sleep, we have an increased chance of dreaming about it. Dreaming about what we’re studying can substantially enhance our ability to understand it.

So sleep well and dream about what you want to learn. It will make the process much easier.

Illusions of Learning

Having the source material easily available for access, like having a textbook at hand or Google open right in front of us, creates the illusion that the material is also available in our brains. There are many ways to fool ourselves that we’re learning something, creating only illusions. Many techniques are very inefficient or just plain useless and we should be very careful and avoid them.

Scintillating Grid Illusion
The white dots are real learning, the black ones are illusions of learning. Credit to Weisstein, Eric W. “Scintillating Grid Illusion.” From MathWorld–A Wolfram Web Resource

What to avoid

Here’s a list of things that are very inefficient and that should be avoided:

  1. Re-reading: The only time rereading text seems to be effective, is if you let time pass between the rereading, so that it becomes more of an exercise in spaced repetition.
  2. Glancing at a solution that is not yours: we need to know how and why of every step of the solution and practice it. This way we make sure that the underlying neural circuitry is created. The information must be persistent in our memory.
  3. Mindless highlighting and underlining: it can even be misleading! Keep highlights and underline to a minimum, one word or sentence per paragraph only.

What to do

If you want maximum learning efficiency and avoid illusions of learning this is what you should start doing and doing a lot:

  1. Recalling: after reading a material, look away from it and try to recall as much as you can or at least the main ideas presented. Research has proved that this is much more effective than re-reading and mind mapping.
  2. Synthesizing notes: writing synthesizing notes on the margin of the book or on other places is a great way to force ourselves to think deep about a concept and simplify it in a smaller, easier way to memorize and understand. The whole process requires a big mental effort which also strengthens our new neuron connections.
  3. Test yourself: it will force you to recall even harder and will give you the right opportunities to make mistakes. Making mistakes is important because every time you do it, you have to think even harder to fix it which strengthens the neural connections needed for learning the material. A test is a safe environment to make mistakes.
  4. Change your learning environment: we unconsciously take visual and mood queues from our surroundings when we are studying and this affects our memory. The more varied the environment where we study, the more diverse our queues are and so we’re more prepared to recall something somewhere different. It’s specially helpful to study on the same place where you’ll be taking a test.

Wrap up

As you can see there’s a lot to learn about learning that nobody teaches us. There many techniques to learn that are very effective for learning new things, as there are special techniques for breathing while singing or running. Even tough it’s something almost instinctive, we can still tweak it and improve it. And many researchers are working hard, making new discoveries on how the brain works and it will help us to improve our learning skills so we must always keep learning how to learn.

For further reading, check out the official text book called “A Mind For Numbers: How to Excel at Math and Science (Even If You Flunked Algebra)” by Barbara Oakley.

A Mind For Numbers: How to Excel at Math and Science (Even If You Flunked Algebra)

Personally, I strongly believe that the most valuable and powerful skill someone can have is the ability to learn new things. It makes us more adaptable and prepared to face new challenges whatever they may be. After taking this course and learning all that I have seen, I believe that I made a great decision. And I hope I motived you to try it too.

Happy learning and Cheers!

Flattr this!