• 累计撰写 6 篇文章
• 累计创建 0 个标签
• 累计收到 1 条评论

# How to think like a programmer

2021-12-20 / 0 评论 / 0 点赞 / 70 阅读 / 12,430 字

“I don’t get JavaScript. I can’t make components from scratch. My mind goes blank when I stare at a blank JavaScript file. I guess I can’t do it because I don’t know how to think like a programmer”.

Sounds familiar? You’re not alone, my friend. Many people faced the same problem when they try to write JavaScript.

No more.Let today be the day where you learn to think like a programmer.

## You don’t believe you can think like a programmer你不信你可以像程序员一样思考

You don’t believe you can think like a programmer because you freeze when you see a blank JavaScript file. But you already know how to think like a programmer.

It’s about using logic to solve problems.

For example, where are you going to go for lunch today? There are COUNTLESS of solutions. But how are you going to solve this problem?

One way to solve this is the process of elimination:

• You don’t want to cook (so you eat out)
• 你不想做饭？（所以你去外面吃）
• You don’t want to go out (so you order takeaway)
• 你不想去外面？（所以你点外卖）
• So you go on Food Panda, Grab, Deliveroo, or another service you know.
• 所以你用美团、饿了么还是其他你知道的服务
• You want healthy food (so Macdonalds is not an option)
• 你想要健康的食物（所以华莱士窜稀套餐不是一个选项）
• You find something that looks appetizing to you.
• 你找到了一些看起来开胃的给你
• And you order the food.
• 然后你下单了

Problem solved!

Understand this: If you can decide how get lunch for yourself, you can think like a programmer.

## How to stop freezing when you see a blank JavaScript file 怎么在你看到空白的JavaScript文件不再麻了

You freeze when you face a blank JavaScript file because you think about how you should structure the code.

• Should you use functions?
• 你应该用函数？
• Should you use classes?
• 你应该用类？
• Or maybe Object-oriented Programming?
• 或者用面向对象编程？

Coders like to talk about coding paradigms. So you’re lured into the illusion that you need to code with ONE of these paradigms.

But you don’t.

Don’t think of structure.

Overcoming coder’s block is simple. Think of the problem you want to solve. You can follow these four steps:

1. Break down the problem into small problems

把这个问题分解到小问题

2. Find solutions to your small problems

找到方案去解决你的小问题

3. Assemble the solutions in a coherent manner

以连贯的方式组合解决方案

4. Refactor and improve

重构和改进

Structure comes in last (during the 4th step, refactoring). If you think of structure, you screw up your brain before you even begin. Thinking of structure before solving the problem leads to complicated, overwhelming, bloated code.

## Errors are your friends 错误是你的朋友

A second reason why you freeze is because you’re afraid of the errors that show up.

Don’t be afraid of errors.

Errors are your friends. We’re lucky to have them.

Think about designers and other professions, when they create something, it’s hard for them to know what’s wrong with their work.

But we get instant feedback through error messages. We know instantly whether our code works. Errors are like angels that gently tell us something is wrong so we can make adjustments and correct things.

## Overcoming Coder’s Block 克服代码阻塞

Think of the problem you want to solve. You can follow these four steps:

1. Break down the problem into small problems
2. Find solutions to your small problems
3. Assemble the solutions in a coherent manner
4. Refactor and improve

### Step 1: Break down the problem into smaller problems. 把这个问题分解到小问题

How do you put an elephant into the fridge?

Here’s what most people would answer:

1. Open the fridge

打开冰箱

2. Put the elephant in

把大象放进去

3. Close the fridge

关上冰箱

Problem solved.

Poor elephant. It looks so sad in the fridge :(

This answer is the best example of why you get stuck when you face a blank JavaScript file. You skipped steps.

If you think logically about the question, you’ll see a few glaring problems that remain unanswered:

1. What fridge are we talking about?

我们说的是什么冰箱

2. What kind of elephant are we talking about?

我们说的大象说什么种类的

3. If the elephant is too huge to fit into the fridge, what do you do?

如果这个大象太大去放进冰箱，你怎么做

4. Where do you find the elephant in the first place?

首先在哪里找到大象

5. How do you transport the elephant to your fridge?

怎么把大象放进你的冰箱

When you code, you need to answer every small question you can think of. That’s why the first step is to break your problem into smaller pieces.

### Step 2: Find solutions to your small problems. 找到方案去解决你的小问题

The second step is to find a solution to each of your small problems. Here, it’s important to be as detailed as possible.

1. What fridge? – the fridge that sits in your kitchen

什么冰箱-你厨房里的冰箱

2. What kind of elephant? – the african bush elephant

什么样的大象-非洲丛林相

3. What if the elephant is too big? – Get a shrink gun (🔫) to shrink the elephant (😎).

如果大象太大怎么做 - 拿一把缩放枪 (🔫) ，去缩放大象(😎).

4. Where do you find the elephant? – Africa

去哪里找到大象- 非洲

5. How do you transport the elephant? – Put it in your bag after you’ve shrunk it, then take a plane back home.

怎么运送大象 - 在你缩放它后放进你的背包，然后坐飞机带回家

Sometimes, you need to dig a few layers in to get the answer you need. In the example above, we can dig deeper into answers 3 and 4.

1. Where do you get the shrink gun? – Borrow from the mad scientist next door.

去哪里拿到缩放枪 - 从隔壁的疯狂科学家借。

2. Where in Africa can you find your elephant? – Addo Elephant Park in South Africa.

在非洲的哪里你可以找到你的大象 - 吧啦吧啦吧公园

Once you have answers to all your smaller problems, you piece them together to solve your big problem.

### Step 3: Assemble the solutions in a coherent manner. 用连贯的方式组合解决方案

So, in the put-elephant-in-fridge example, you can probably follow the following steps:

1. Get a shrink gun from the scientist next door

从隔壁的科学家得到一把缩放枪

2. Fly to South Africa

飞到南非

3. Travel to Addo Elephant Park

到达吧啦吧啦吧公园

4. Find an elephant in the park

在公园找到一个大象

5. Shoot the elephant with the shrink gun

用收缩枪射击大象

6. Put the shrunk elephant in your bag

缩放大象装进你的背包里

7. Travel back to the airport

返回机场

8. Fly back to your country

飞到你的国家

9. Travel to your house

到家

10. Put the elephant in your fridge

把大象放进你的冰箱

Problem solved.

As interesting as it sounds, you wouldn’t be capturing elephants and putting them into fridges with JavaScript anytime soon. Let’s go through a real example instead.

## Let’s use a real example. 用一个真实的例子。

Let’s say you want to a create button that, when clicked, shows you a sidebar.

### Breaking down the problem 拆分这个问题

The first step to building this button-and-sidebar component is to break down the component into smaller pieces. Here are a few problems you may identify:

1. What is the markup of this button?

这个按钮的标记是什么？

2. How should the button look?

按钮应该长这么样

3. What happens when the button gets clicked once?

在点击一次会发生什么

4. What happens when the button gets clicked again?

再次点击会发生什么

5. What happens when the button gets clicked a third time?

第三次点击会发生什么

6. What is the markup of this sidebar?

这个侧边栏的标记是什么？

7. How does the sidebar look when it is shown?

侧边栏显示的时候应该长什么样

8. How does the sidebar look when it is hidden?

侧边栏隐藏的时候应该长什么样

9. How does the sidebar show up?

侧边栏怎么显示

10. How does the sidebar go away?

侧边栏怎么隐藏

11. Should the sidebar show up when the page loads?

页面加载时是否应该显示侧边栏

Let’s answer each of the questions:

What is the markup of this button?

The markup is an <a> tag with a class of .btn.

<a href="#" class="btn">Click me</a>


How should this button look? 按钮应该长这么样

This button should have the following CSS:

.btn {
display: inline-block;
font-size: 2em;
background-color: #1ce;
color: #fff;
text-transform: uppercase;
text-decoration: none;
}


What happens when the button gets clicked once? Twice? Three times? 点击一次按钮后会发生什么？ 两次？ 三次？

• Click once: Sidebar shows up

点击一次：按钮显示

• Click twice: Sidebar goes away

点击2次：按钮隐藏

• Click 3 times: Sidebar shows up again

点击3次：按钮再次显示

What is the markup of this sidebar? 这个侧边栏的标记是什么？

The sidebar should be a <div> that contains a list of links:

<div class="sidebar">
<ul>
</ul>
</div>


How does the sidebar look when it is shown? 侧边栏显示的时候应该长什么样

The sidebar should be placed at the right of the window. It needs to be fixed in place so the user sees it. It should be 300px wide…

When you finish solving the problem, you may end up with CSS that looks similar to the following:

.sidebar {
position: fixed;
top: 0;
bottom: 0;
right: 0;
width: 300px;
background-color: #333;
}

.sidebar ul {
margin: 0;
}

.sidebar li {
list-style: none;
}

.sidebar li + li {
border-top: 1px solid white;
}

.sidebar a {
display: block;
color: #fff;
text-decoration: none;
}


How does the sidebar look when it is hidden? 侧边栏隐藏的时候应该长什么样

The sidebar should be shifted 300px to the right, so it is off the screen.

When you answer this question, another two may pop into your mind:

1. How do you know whether the sidebar is shown or hidden?

你怎么知道侧边栏是显示还是隐藏？

2. How do you style the hidden sidebar?

你怎么设置隐藏侧边栏的样式？

Let’s answer them as well.

How do you know whether the sidebar is shown or hidden? 你怎么知道侧边栏是显示还是隐藏？

If the sidebar has a .is-hidden class, the sidebar should be hidden from view. Otherwise, it should be visible.

How do you style the hidden sidebar? 你怎么设置隐藏侧边栏的样式？

We use translateX to shift the sidebar 300px to the right since transform is one of the better properties for animation. Your styles then becomes:

.sidebar.is-hidden {
transform: translateX(300px);
}


How does the sidebar show up? 侧边栏怎么显示

The sidebar cannot appear immediately. It needs to move from the right (where it’s hidden from view) to the left (where it becomes visible).

If you know your CSS, you’ll be able to use the transition property. If you don’t, you’ll be able to find your answer through Google.

.sidebar {
/* other properties */
transition: transform 0.3s ease-out;
}


How does the sidebar disappear? 边栏如何消失？

It should disappear the same way it appears, in the opposite direction. With this, you don’t have to write any additional CSS code.

**Should the sidebar show up when the page loads? **页面加载时是否应该显示侧边栏

Nope. Given what we have, we can add an is-hidden class in the sidebar markup and the sidebar should remain hidden

<div class="sidebar is-hidden">
</div>


Now, we’ve answered almost everything, except one – what happens when the button gets clicked once? Twice? Three times?

Our answer above was too vague. We know the sidebar should appear when you click on it, but how? The sidebar should disappear when you click on it again, but how?

At this point, we can answer this question again with much more details. But before that, how do know when you clicked on a button?

How to know when you click on a button. 怎么知道何时单击按钮

If you know your JavaScript, you know you can add an event listener to the button and listen for a click event. If you don’t know, you’ll be able to google it.

Before you add an event listener, you need to find the button from the markup with querySelector.

const button = document.querySelector('.btn')

console.log('button is clicked!')
})


What happens when the button is clicked once? 单击一次按钮会怎样？

When the button is clicked once, we should remove the is-hidden class so the button shows up. To remove a class in JavaScript, we use Element.classList.remove. This means we need to select the sidebar first.

const button = document.querySelector('.btn')
const sidebar = document.querySelector('.sidebar')

sidebar.classList.remove('is-hidden')
})


What happens when the button is clicked twice? 两次单击该按钮会发生什么？

When the button is clicked again, we should add the is-hidden class back to the sidebar so it disappears.

Unfortunately, we can’t detect how many times a button is clicked with an event listener. The best way, then, is to check if the class is-hidden is present on the sidebar already. If it is, we remove it. If it’s not, we add it.

const button = document.querySelector('.btn')
const sidebar = document.querySelector('.sidebar')

if (sidebar.classList.contains('is-hidden')) {
sidebar.classList.remove('is-hidden')
} else {