Writing code for people

Alexey Ivanov, Evil Martians

Writing code for people

Alexey Ivanov, Evil Martians

Evil Martians

Evil Martians

Let's talk about writing

Do you know how to write?

Writing code is the same

Have you been in these situations?

This is a common situation

Most of programming tutorials and books teach how to write code that can be understood by the computer and do some stuff with it.

Very few books and tutorials teach how to write code that other people can read and understand.

But it's not a good situation

You write code once. But you and other people will be reading and modifying it tens or even hundreds of times after that.

So it's crucial to write code that is readable, reusable, and refactorable.

Writing code for people

It's a skill that can be learned

As with any other skill, if you will be mindful of what you are writing and spend enough time training, you will become better at this.

Talk structure

  1. Writing the code - principles, rules, style guides, and linters.
  2. Reading the code - how to train yourself to become a better writer.

Writing the code

Writing the code

  1. Clean code.
  2. Easy to understand code.
  3. Code that shares context.

Clean code

Clean code

Clean code Select a code style

There are tons of existing style guides:

Choose any of them. It's not important which one. Don't spend time on that.

Clean code Add linters

Linters usually have excellent documentation about when and why to use each rule.

Clean code Add standard config for linters

The good thing about using a popular style guide is the fact that it is already automated.

Clean code Enable automatic linting and fixing

Easy to understand code

Easy to understand code

  1. Readability.
  2. Complexity.
  3. Reading flow.

Readability

Readability Use meaningful and pronounceable variable names

Bad:

        const yyyymmdstr = moment().format("YYYY/MM/DD");
      

Good:

        const currentDate = moment().format("YYYY/MM/DD");
      

Readability Use searchable names

Bad:

        setTimeout(blastOff, 86400000);
      

Good:

        const MILLISECONDS_IN_A_DAY = 86_400_000;
        setTimeout(blastOff, MILLISECONDS_IN_A_DAY);
      

Readability Function arguments (2 or fewer ideally)

Bad:

        function createMenu(title, body, buttonText, cancellable) {
          // ...
        }
        
        createMenu("Foo", "Bar", "Baz", true);
      

Readability Function arguments (2 or fewer ideally)

Good:

          function createMenu({ title, body, buttonText, cancellable })
            // ...
          }
           
          createMenu({
            title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true
          });
        

Readability Further reading

Complexity

Complexity Automation

You can automate detection of such things. For example with Eslint:

Be careful. Following these rules blindly can produce harder to read code.

Reading flow

Reading flow

Sometimes it is better to break complexity rules to make the reading flow easier.

Reading flow Place things close to each other

          dropdown/
            locale/
              en.json
              jp.json
            index.js
            index.test.js
            readme.md
            styles.css
      

Code that shares context

Example Replacing GA with GTM

Old code:

          window.ga("send", {
            hitType: "event",
            eventCategory: "Videos",
            eventAction: "play",
            eventLabel: "Fall Campaign",
            eventValue: 10
          });
      

Example Replacing GA with GTM

Old code:

          window.ga("send", {
            hitType: "event",
            eventCategory: "Page",
            eventAction: "Navigate",
          });
      

Example Replacing GA with GTM

New code:

          window.dataLayer.push({
            category: "Videos",
            action: "play",
            label: "Fall Campaign",
            value: 10
          });
      

Example Replacing GA with GTM

New code:

          window.dataLayer.push({
            category: "Page",
            action: "Navigate",
          });
      

Example Replacing GA with GTM

Solution:

          const event = { /* ... */ }
          const eventPlaceholder = {
            label: undefined, value: underfined
          };
           
          window.dataLayer.push({ ...eventPlaceholder, ...event });
      

But how do you share this knowledge?

  1. You can't just leave the code" as is" – next developer can delete it while refactoring, and then they will spend eight more hours debugging it.
  2. You can't ask other people to review this code without telling them what it is doing and why.
  3. Other people can't update and maintain this code.
          /* 
            GTM sets all event fields as global variables inside itself,
            so until we rewrite them, they will have old values. Because
            label and value are optional fields, we need to unset them
            for the next events explicitly. Relevant docs:
           
            - https://developers.google.com/tag-manager/devguide
            - https://support.google.com/tagmanager/answer/6164391?hl=en
          */
      

What is context?

Code can't explain why the program is being written, and the rationale for choosing this or that method. Code cannot discuss the reasons certain alternative approaches were taken.

Jeff Raskin

What is context?

For example:

        /* A binary search turned out to be slower than the
           Boyer-Moore algorithm for the data sets of interest,
           thus we have used the more complex, but faster method
           even though this problem does not at first seem
           amenable to a string search technique. */
      

Jeff Raskin

CSS example

          @media (--sm-scr) {
            .input {
              font-size: 16px; /* prevents iOS auto-scale on focus */
            }
          }
      

React Source

GIT Source

When to comment

Links

Summary of the first part

  1. Clean code.
  2. Easy to understand code.
    1. Readability.
    2. Complexity.
    3. Reading flow.
  3. Code that shares context.

Reading the code

Reading the code

  1. Code reading.
  2. Code reviews.
  3. Pair Programming.

Code reading

Code reading

Douglas Crockford — Goto There and Back Again starting from 27:15

Code reading

Crockford's method:

  1. Do it every day.
  2. Discuss approaches, patterns, and possible solutions.
  3. Don't judge. Don't use results as metrics.

Code reading

Who should read:

  1. Reading by the author - faster to do, better at describing context, but fewer chances to find problems.
  2. Reading by the other person - slower, requires more steps, more useful feedback on writing.

Code reading

You can use methodology from usability testings for the additional effect:

Read more: Thinking Aloud: The #1 Usability Tool

Code reading

Read the code from open-source projects that you use together in the same way:

Some projects to start from

Code review

Code review

Principles of the clean code apply to commits and PRs as well:

Code review Split to many small PRs

If you have large PR - split them to the smaller parts:

  1. Refactoring filenames? Create PR.
  2. Changing the React component that is used in multiple places? Create PR.
  3. Making new utility for everyone to use? Create PR.

Code review Describe context

You can (and should) use commit messages and PR description to describe the task's context:

  1. What was the task?
  2. Why did you choose to solve it in this way and not another?

Code review Advance preparation

Things that should be done before code review:

Code review Can't split to different PRs?

  1. Split large PRs that need to be merged all at once in the separate commits that only do one thing.
  2. Give each commit a meaningful name.
  3. Before pushing to upstream, make your commit history beautiful: Squash, rename, and clean up your commits.

Code review

Links:

Pair programing

Pair programing

How to use to become a better writer:

Summary of the talk

Writing:

  1. Clean code.
  2. Easy to understand code.
    1. Readability.
    2. Complexity.
    3. Reading flow.
  3. Code that shares context.

Reading:

  1. Code reading.
  2. Code reviews.
  3. Pair Programming.

Writing code for people

Alexey Ivanov, Evil Martians

Twitter: @iadramelk
Slides: https://iadramelk.github.io/code-reading/