工厂用抽象类比接口

by Samer Buna

通过Samer Buna

用简单的现实类比解释硬编码概念 (Hard Coding Concepts Explained with Simple Real-life Analogies)

如何向5岁的孩子解释诸如流,promise,lint和声明性编程之类的编码概念 (How to explain coding concepts like streams, promises, linting, and declarative programming to a 5-year-old)

I love thinking about coding concepts by comparing them to familiar things we know in life. There are so many analogies out there about coding concepts. Some of them are good while others are confusing, mainly because they focus on partial aspects of a concept while ignoring many others. This article will summarize some of the analogies that I think best fit a few coding concepts in complete ways.

我喜欢通过将编码概念与我们生活中熟悉的事物进行比较来思考编码概念。 关于编码概念有很多类比。 其中一些很好,而另一些却令人困惑,主要是因为它们专注于概念的部分方面而忽略了许多其他方面。 本文将总结一些我认为最适合某些编码概念的类比。

Update: This article is now part of my book “The Professional Programmer”.

更新:本文现在是我的“专业程序员”一书的一部分。

Read the updated version of this content, and more programming advice at jscomplete.com/pro-programmer.

阅读此内容的更新版本,以及在jscomplete.com/pro-programmer上的更多编程建议。

I will start with simple concepts and move on to harder ones. Let’s start with coding itself. Coding can be compared to writing cooking recipes. A recipe in this analogy is the program and the cook is the computer. A recipe is a list of instructions for a cook to follow and a program is a list of instructions for a computer to execute.

我将以简单的概念开始,然后继续介绍较难的概念。 让我们从编码本身开始。 可以将编码与编写烹饪食谱进行比较。 打个比方,程序就是程序,而厨师就是计算机。 食谱是厨师要遵循的指令列表,程序是计算机要执行的指令列表。

This is a very simple analogy given that a recipe is written in a human language and a program is written in a computer language and those are very different languages (unless your recipes have closures and promises!). There are also not a lot of unexpected things to plan for in a recipe while a computer program will have many. Regardless of its simplicity, it is a good way to show how a computer carries out a list of instructions sequentially. It also shows where one instruction line can use any result from executing prior instruction lines.

这是一个非常简单的类比,因为配方是用人类语言编写的,而程序是用计算机语言编写的,并且它们是非常不同的语言(除非您的配方具有闭包和承诺!)。 在计算机程序中会有很多意外的事情要计划的食谱中,也没有很多。 不管它的简单性如何,它都是显示计算机如何顺序执行指令列表的好方法。 它还显示了一条指令行可以在哪里使用执行先前指令行的任何结果。

Some recipes will even have if-statements: if cooking for 2, 4 or 8! Some recipes will have loops: keep beating that mix until…

有些食谱甚至会带有if语句 :如果烹饪2、4或8! 有些食谱会有循环 :继续搅拌直到……

I also like this analogy because of all the ready items and tools that you can use in your recipes — like the cake mix that you can use to make cupcakes and that specially-shaped pan that makes it so much easier to create cupcakes.

我也喜欢这个比喻,因为您可以在食谱中使用所有现成​​的物品和工具,例如可以用来制作纸杯蛋糕的蛋糕混合物,以及可以轻松制作纸杯蛋糕的特殊形状的锅。

The use of ready items and tools is like including and using a package of code written by others in your own code.

使用现成的项目和工具就像在他人的代码中包含并使用其他人编写的代码包。

// The making of a cupcake// First steps:
$ npm install cake-mix$ npm install cupcake-pan

NPM is the package manager for Node.js, which a very popular framework for writing JavaScript applications. In this analogy, Node.js is like the kitchen itself. It allows you to execute lines in your recipes by using built-in modules like your oven and sink.

NPMNode.js的软件包管理器, Node.js是一个非常流行的用于编写JavaScript应用程序的框架 。 以此类推,Node.js就像厨房一样。 它允许您使用烤箱和水槽等内置模块在配方中执行代码行。

Speaking of unhealthy food, this next analogy is for learning how to code and is compared to eating habits. I particularly LOVE this analogy and what it conveys because it helps me to stay on track in my code learning journey. For me, this began in high school and will continue until my brain reaches its last instruction: die();

说到不健康的食物,下一个类比是为了学习如何编码并与饮食习惯进行比较。 我特别喜欢这种类比及其传达的含义,因为它可以帮助我在代码学习过程中始终如一。 对我来说,这是从高中开始的,一直持续到我的大脑达到最后一条指令为止:die();

学习编码 (Learning To Code)

Learning to code is like trying to lose weight. This analogy applies to learning anything really, but learning to code is a special match here.

学习编码就像试图减肥。 这个类比适用于真正学习任何东西,但是在这里学习编码是一种特殊的匹配。

“Losing Weight” is a negative term. We should really call it “Gaining Health.” In that sense, it is very much comparable to “Gaining Knowledge.” The educational resources you have available to you are like your food options. Some are just okay, some are great, and some are completely bad for you. Eating healthy and exercising are the main two activities that will help you gain health. Similarly, consuming good educational resources and practicing coding by hand are the main two activities that will help you gain good coding knowledge.

“减肥”是一个否定术语。 我们真的应该称其为“获得健康”。 从这个意义上讲,它与“获取知识”非常相似。 您可以使用的教育资源就像您的饮食选择。 有些还可以,有些很棒,有些完全对您不利。 健康饮食和锻炼是可以帮助您获得健康的两个主要活动。 同样,消耗大量的教育资源和手工练习编码是可以帮助您获得良好编码知识的主要两项活动。

So how do you learn “healthy”? When you commit to eating healthy, you use filters like organic, local, reduced-fat, grass-fed, and non-gmo. It is exactly the same with healthy educational resources except these labels are not yet as clear. I hope educational resources will someday have verifiable and relevant labels too. Maybe labels like “not-sponsored,” “no-marketing,” “approved-by-experts,” “tightly-edited,” and “dragons-ahead.”

那么,您如何学习“健康”呢? 当您承诺健康饮食时,可以使用有机本地低脂草饲非转基因等过滤器。 健康的教育资源完全相同,只是这些标签尚不清楚。 我希望有一天教育资源也将具有可验证的相关标签。 也许有“不赞助”,“不行销”,“经专家批准”,“经过严格编辑”和“超前”的标签。

Yet, instead of filtering by the content, you can easily filter by the good brands. I do that with food too. I know and trust a few brands and I mostly use those. It is easier. With educational resources, there are some brands (publications and people) that you should just follow all the time.

但是,除了按内容过滤之外,您还可以轻松按好品牌过滤。 我也用食物做。 我知道并信任一些品牌,而我主要使用这些品牌。 更容易。 借助教育资源,您应该始终遵循一些品牌(出版物和人物)。

After filtering your knowledge intake to only the good resources, you just need to exercise! Practice everything you learn, but not just by re-doing exactly what you learned. Also challenge yourself to do something slightly different around the topics that you learned. If you are lucky, you will get stuck! Then you will permanently learn something else when you get unstuck.

将您的知识吸收仅过滤到好的资源之后,您只需要锻炼即可! 练习所学的一切,而不仅仅是重做学到的东西。 还要挑战自己,围绕所学主题做些不同的事情。 如果幸运的话,您会被卡住! 然后,当您被卡住时,您将永久学习其他东西。

Exercise is for both the body and the mind.

锻炼既有益身心,又有益身心。

变数 (Variables)

Variables are used in computer programs to hold data. This is a very simplified statement and it is by many measures simply wrong.

在计算机程序中使用变量来保存数据 。 这是一个非常简化的陈述,并且从很多方面来看都是错误的。

Variables do not hold data. They just point to it. Data is held in the computer’s memory. You can compare variables to the labels you place on your email messages (or notes, or files).

变量不保存数据。 他们只是指出这一点。 数据保存在计算机内存中。 您可以将变量与放置在电子邮件(或便笺或文件)上的标签进行比较。

All code samples in this article are written in JavaScript. JavaScript is a very easy to learn computer language.

本文中的所有代码示例均使用JavaScript编写。 JavaScript是一种非常容易学习的计算机语言 。

In Gmail, a label is a pointer to an email or a list of emails. Many labels can point to the same email. This is similar to assigning another variable to an existing variable:

在Gmail中,标签是指向电子邮件或电子邮件列表的指针。 许多标签可以指向同一封电子邮件。 这类似于将另一个变量分配给现有变量:

let work = [email1, email2, email3];let important = work;

Both work and important are now labels that point to the exact same list of emails.

现在,工作标签和重要标签都是指向完全相同的电子邮件列表的标签。

Some variables represent constant references. They cannot be changed. This is like the “sent” label in Gmail. While we can change the work label above and make it point to a different list of emails, we cannot change the label sent. You cannot point the sent label to a different list of emails. You can only make it point to more emails.

一些变量表示常量引用 。 它们无法更改。 这就像Gmail中的“已发送 ”标签。 尽管我们可以更改上面的工作标签并使其指向其他电子邮件列表,但是我们无法更改已发送的标签。 您不能将发送的标签指向其他电子邮件列表。 您只能使其指向更多电子邮件。

const sent = [];
// You cannot change the meaning of sent now// But you can add more values to it:
sent.push(new Email());

错误与异常 (Errors and Exceptions)

A programmer’s expertise is largely about how to deal with errors. Expert programmers love errors because, for them, errors mean progress.

程序员的专业知识在很大程度上与如何处理错误有关。 专家程序员喜欢错误,因为对于他们而言,错误意味着进步。

Sometimes we expect to see these wonderful red messages and if we do not we know that the code is simply wrong!

有时我们希望看到这些奇妙的红色消息,如果不知道,我们将知道代码根本是错误的!

I love the phrase “listen to your code” because I think code evolves by communicating to us using errors.

我喜欢“ 您的代码”这一短语,因为我认为代码是通过使用错误与我们沟通来发展的。

This is exactly like raising kids.

这就像抚养孩子一样。

The most important parenting concept that I realized, with practice, is how kids communicate by misbehaving. This is because they do not have a logical brain yet. I think programs do the exact same thing. They also communicate by misbehaving (producing errors) because programs are not completely logical. Your task as a programmer is to add more logic in the code to handle the cases that originally produced errors. This is just like how a parent’s task is to teach the misbehaving kid what is wrong with that bad behavior and what to do differently next time.

通过实践,我认识到最重要的育儿概念是孩子如何通过行为不端进行交流。 这是因为他们还没有逻辑大脑。 我认为程序做的完全一样。 它们还通过行为不当(产生错误)进行通信,因为程序并不完全符合逻辑。 作为程序员的任务是在代码中添加更多逻辑,以处理最初产生错误的情况。 这就像父母的任务是教导行为不端的孩子该不良行为有什么问题以及下次如何做一样。

Some errors are not recoverable and a program encountering those should just exit (and be rebooted). This is like if your heart stops. There is not much that can be done except to reboot it with an electric shock. This is why we monitor our programs and reboot them when they get to that state. Luckily, the process of rebooting a program is not as dramatic.

有些错误是无法恢复的,遇到这些错误的程序应该退出(并重新启动)。 这就像你的心脏停止跳动一样。 除了触电重启外,没有什么可以做的。 这就是为什么我们监视程序并在它们进入该状态时重新启动它们的原因。 幸运的是,重新启动程序的过程并不那么复杂。

Most errors that happen during the early development of programs help improve these programs so that the errors never happen. This is how good kids are raised. They do not repeat the misbehaving because now they have good logic to guide them in a good direction.

在程序的早期开发过程中发生的大多数错误都有助于改进这些程序,从而使这些错误永远不会发生。 这就是养育好孩子的方式。 他们不会重复这种行为,因为现在他们有很好的逻辑来指导他们朝着正确的方向发展。

Some errors evolve to be exceptions. Exceptions are expected errors. Errors that we can plan for and recover from. The best coding example here is a Network Connection error while we make a program, for example, download some data. This is very much expected because we know network connections could be unreliable so we plan for that error. When that error happens, let’s label the task of downloading that data as incomplete. Queue it somewhere, and re-try it at a later time (see below for an analogy for queuing).

一些错误演变为例外。 异常是预期的错误。 我们可以计划并从中恢复的错误。 最好的编码示例是我们制作程序时的网络连接错误,例如,下载一些数据。 这是非常可预期的,因为我们知道网络连接可能不可靠,因此我们为该错误做好了准备。 当发生该错误时,让我们将下载该数据的任务标记为不完整。 将其放入队列中,然后在以后重试(有关排队的类比,请参见下文)。

What we did with this planned exception is give the computer a different set of instructions (a different recipe) to do when that error happens. We do exactly that with our kids as well. We give them instructions about what to do in certain future scenarios that we expect (or fear in this case).

对于该计划的异常,我们所做的就是在发生错误时为计算机提供一组不同的指令(不同的配方)。 我们也与我们的孩子一起做到这一点。 我们向他们提供有关我们期望的某些未来方案(或在这种情况下感到恐惧)的操作说明。

// Hey kidsif (stranger.offersYou(chocolate)) {  doNotAccept();  doNotTalkTo(stranger);  walkAway();}
if (stranger.triesToForceYouToDoSomething()) {  screamFor(help);  runAway();  call(911);}

React式编程和流 (Reactive Programming and Streams)

Reactive programming is a popular method for writing code that is based on reacting to changes. It is inspired by our everyday life and how we take actions and communicate with others. When performing everyday life activities, we try to multitask when we can but the brain cannot multitask no matter how hard we try. The only way we humans can multitask is to switch tasks and split them efficiently during their lifetime. This makes more sense when the tasks that we need to do require some amount of waiting, which is almost always the case. We actually always switch-tasks, even when we are not aware of it.

响应式编程是一种基于对更改做出React的流行代码编写方法。 它的灵感来自于我们的日常生活以及我们如何采取行动并与他人沟通。 在进行日常生活活动时,我们会尽力进行多任务处理,但是无论我们多么努力,大脑都无法完成多任务处理。 我们人类可以执行多任务的唯一方法是切换任务,并在其生命周期内高效地拆分任务 。 当我们需要完成的任务需要一定数量的等待时 (这几乎总是这种情况),这更有意义。 实际上,即使我们不了解任务,我们也总是会切换任务。

Reactive programming is simply to program using, and relying on, events instead of the order of lines in the code. Usually, this involves more than one event, and those events happen in a sequence over time. We call this sequence of events a “stream”.

响应式编程仅是使用事件并依靠事件进行编程,而不是使用代码中的行顺序进行编程。 通常,这涉及多个事件,并且这些事件会随着时间顺序发生。 我们将此事件序列称为“ ”。

Think of events as anything that might happen in the future. For example, you know that Jane (a store owner) is always tweeting interesting things on Twitter. Every time she tweets something we call that an “event”. If you look at Jane’s Twitter feed, you have a sequence of “events” happening over time (a stream of events). Reactive programming is named so because we get to “react” to those events. For example, imagine that you are waiting for Jane to tweet a promotional code about something cool she sells in her store. You want to “react” to that tweet and buy the cool thing using the promotional code. In a simplified picture, that is exactly what Reactive programming is all about.

将事件视为将来可能发生的任何事情。 例如,您知道Jane(商店老板)总是在Twitter上发布有趣的东西。 每次她发布推文时,我们都将其称为“事件”。 如果您查看Jane的Twitter提要,则随着时间的流逝会发生一系列“事件”(事件流)。 响应式编程之所以这样命名,是因为我们可以对这些事件“做出React”。 例如,假设您正在等待Jane发出有关她在商店中出售的精美商品的促销代码。 您想对该推文“做出React”,并使用促销代码购买有趣的东西。 在简化图中,这正是Reactive编程的全部目的。

To be able to react to an event, we have to be monitoring it. If we do not track the event, we will never know when to react to it. On Twitter, to monitor the events of Jane tweeting, we follow Jane and set our phone to notify us every time she tweets. When she does, we look at the tweet and make a decision on whether we need to further react to it or not.

为了能够对事件做出React,我们必须对其进行监视 。 如果我们不跟踪事件,我们将永远不知道何时对该事件做出React。 在Twitter上,为了监视Jane的推文事件,我们关注Jane并设置手机以在她每次发推文时通知我们。 当她这样做时,我们会查看该推文,并决定是否需要对此进一步做出React。

In reactive programming, the process of monitoring an event is known as listening or subscribing to the event. This is, in fact, very similar to subscribing to a newsletter. When you subscribe to a newsletter on the Web, you supply your email address. Every time there is a new issue of the newsletter your email address will be used as the way for you to get a copy of the issue. Similarly, we subscribe to an event stream with a function. Every time there is a new event, the stream will use the function to enable our code to react to the event. In this analogy, the newsletter platform is the event stream. Every issue of the newsletter is an event and your email is the function you use to subscribe to the event stream.

在React式编程中,监视事件的过程称为侦听或订阅事件。 实际上,这与订阅新闻通讯非常相似。 当您在网络上订阅新闻时,您将提供您的电子邮件地址。 每次有新的时事通讯时,您的电子邮件地址都将用作获取该问题副本的方式。 同样,我们使用函数订阅事件流。 每当出现新事件时,流将使用该函数来使我们的代码对事件做出React。 以此类推,新闻通讯平台就是事件流。 时事通讯的每一期都是一个事件,您的电子邮件是您用来订阅事件流的功能。

Now imagine a dynamic newsletter that allows you to select topics and send you only the news items that match your topics. You are basically filtering the newsletter issues to your liking and that is something we can do on event streams as well. Also, imagine that you have subscribed to several newsletters using different email addresses. You later decided that you want all issues of the newsletters to be sent to a new single email address. One easy thing you can do is to set an email rule that forwards any issues from any newsletter to the new email address. You are basically merging multiple newsletter issues into one email address, which is another thing we can do with event streams.

现在想象一个动态新闻通讯,它使您可以选择主题,并仅向您发送与主题匹配的新闻。 您基本上是根据自己的喜好过滤新闻通讯问题,这也是我们可以在事件流上执行的操作。 另外,假设您已使用不同的电子邮件地址订阅了多个新闻通讯。 后来您决定要将所有新闻通讯发送到新的单个电子邮件地址。 您可以做的一件简单的事情就是设置一个电子邮件规则,将任何新闻从任何新闻通讯转发到新的电子邮件地址。 您基本上是将多个新闻通讯合并到一个电子邮件地址中,这是我们可以使用事件流完成的另一件事。

Another way to think about event streams is to compare them to regular arrays. They are actually very similar. Arrays are a sequence of values in space while event streams are a sequence of values over time. In reactive programming, all the functional operations that we can do on an array. Filtering, reducing, mapping, combining, piping can all be done on event streams. We can filter an event stream, reduce the values of an event stream, map an event stream to another, combine streams, and make one stream an input to another. These are all options that yield new streams of values over time.

思考事件流的另一种方法是将它们与常规数组进行比较。 它们实际上非常相似。 数组是空间中的一系列值,而事件流是一段时间内的一系列值。 在React式编程中,我们可以在数组上执行的所有功能性操作。 过滤,归约,映射,合并,管道化都可以在事件流上完成。 我们可以过滤一个事件流,减少一个事件流的值,将一个事件流映射到另一个,组合流,并将一个流作为另一个的输入。 这些都是随着时间的流逝产生新价值流的选择。

回调和承诺 (Callbacks and Promises)

Imagine you ask someone to give you something that needs some time to be prepared. They take your order and your name and tell you to wait to be called when your order is ready. After a while, they call your name and give you what you asked for.

想象一下,您要求某人给您一些需要一些时间准备的东西。 他们会接受您的订单和您的姓名,并告诉您在订单准备就绪时等待被呼叫。 一段时间后,他们会叫您的名字,并给您您所要的。

The name you originally gave them is the callback function here. They called it with the object that was requested.

您最初给他们提供的名称是此处的回调函数。 他们用请求的对象调用它。

This is like when you order a latte from Starbucks (in the store, not in the drive-thru). They synchronously record your order and name and then you wait until your name is called. When that happens, you receive your latte:

就像您从星巴克(Starbucks)订购拿铁咖啡(在商店中,而不是直通车)。 他们同步记录您的订单和姓名,然后您等待直到您的姓名被叫出。 发生这种情况时,您会收到拿铁咖啡:

starbucks.makeMeALatte({ type: 'Vanilla', size: 'Grande' }, Samer);
// "Samer" here is the callback function.// When the Latte is ready, the barista will call Samer // with the ready object// We define a function Samer to process the ready object
function Samer(readyLatte) {  // drink readyLatte}

Now imagine you ask someone to give you something, but they give you something else. Let’s call it a mystery object. They promise you that this mystery object might eventually turn into the thing you originally asked for.

现在想象您要某人给您一些东西,但他们却给您其他东西。 我们称之为神秘对象。 他们向您保证,这个神秘物体最终可能会变成您最初要求的东西。

This promise mystery object can turn into one of two possible forms. One form is associated with success and the other with failure.

这个承诺神秘物体可以变成两种可能形式之一。 一种形式与成功相关,另一种形式与失败相关。

This is like when we ask a chicken for a chick and the chicken gives us an egg. That egg might successfully turn into a chick or it might die and be useless.

这就像我们向小鸡要鸡,而鸡给我们一个蛋。 那个鸡蛋可能成功地变成了小鸡,或者可能死亡并且毫无用处。

const egg = chicken.makeChick();   // It's a promise!
egg.then(chick => raiseChick())    // Success outcome   .catch(badEgg => throwBadEgg()) // Fail outcome

队列和堆栈 (Queues and Stacks)

When we work with elements of data, there are two popular data structures to store and use these elements: A LIFO Stack and a FIFO queue.

当我们处理数据元素时,有两种流行的数据结构可以存储和使用这些元素:LIFO 堆栈和FIFO 队列

LIFO stands for Last In First Out and FIFO stands for First In First Out.

LIFO代表先进先出 ,FIFO代表先进先出

The simplest analogy of a data stack is the stack of dirty dishes in your sink. When you are done using a dish, you stack it on top of the existing dirty dishes until you are ready to wash them.

数据堆栈的最简单的类比是水槽中的脏盘子堆栈。 使用完盘子后,将其叠放在现有的脏盘子上,直到准备好清洗为止。

When you are ready to wash them, you take the last dirty dish that you stacked and you wash that. In computer terminologies, we say you “popped” a dish.

准备好清洗它们时,请拿起堆积的最后一个脏盘子,然后清洗。 用计算机术语来说,我们说您“弹出”一道菜。

The last dish you stacked is the first dish you washed. This is LIFO.

您堆放的最后一道菜是您洗过的第一道菜。 这是LIFO。

The simplest analogy of a data queue is the line of people that forms in front of a checkout or order station. When you are ready to pay for your groceries and take them home, you might need to queue yourself in a line until it is your turn.

数据队列最简单的类比是在结帐站或订单站前形成的一排人。 当您准备为杂货付款并将其带回家时,您可能需要排队等候直到轮到您了。

The first person to arrive at that queue will be the first person to be done with it. This is FIFO.

第一个到达该队列的人将是第一个处理该队列的人。 这是FIFO。

配对编程 (Pair Programming)

You can drive your car on your own when you go to familiar places, but when it is time to go somewhere far for the first time you use a GPS. If you have someone else in the car with you, a better option would be to have them navigate by giving you the instructions on where to turn next. If you do not follow the instructions and end up taking a bad turn, they will let you know immediately and advise you on how to correct it.

当您去熟悉的地方时,您可以自己开车,但是当您是第一次使用GPS到某个地方的时候。 如果您有其他人在车上,最好的选择是让他们导航,然后向您提供下一个转弯的指示。 如果您不按照说明进行操作,而最终转弯不正确,他们会立即通知您,并为您提供纠正建议。

Having a navigator next to you when you drive is like having a pair-programmer. You are not driving alone. You are a team with the same goal: to arrive at your destination safely, without any problems, and with the least amount of time and effort.

开车时在您旁边有一个导航器,就像有一个配对编程器。 您不是一个人开车。 您是一个具有相同目标的团队:安全,无问题,花费最少的时间和精力到达目的地。

You can probably do it yourself without a human navigator or a fancy GPS by using the old-school way and checking a map before you leave. If needed, you can check the map again. If you check the map while driving, you might accidentally hit a curb or put a dent in the car. If you stop to check the map, you will be losing time. Without that pair navigator, you are not as safe and/or the journey will take a lot longer.

您可以通过使用老式方法并在离开前检查地图的方式在没有人工导航仪或精美GPS的情况下自行完成操作。 如果需要,您可以再次检查地图。 如果您在开车时检查地图,可能会意外撞到路缘或在汽车上留下凹痕。 如果您停止检查地图,则将浪费时间。 如果没有该配对导航器,您将不那么安全,并且/或者旅行将花费更长的时间。

The experience of your pair navigator might also teach you new things. They might know of a new shortcut that you do not and one that is not on the map. You learn from their relevant experience, and this is beyond valuable.

配对导航器的经验可能还会教给您新的事物。 他们可能知道您没有的新快捷方式以及地图上没有的快捷方式。 您可以从他们的相关经验中学习,这是无价的。

If you need to go to two destinations and you have two cars. You might be tempted to think that it would be faster to drive solo and do the destinations in parallel. This might be faster in the short term, but all things considered, time might not be the most important factor here. When it comes to computer programs, using one car and making sure it is dent-free at the end of both journeys might be a far more important factor. This why we love pair programming.

如果您需要前往两个目的地并且有两辆车。 您可能会认为,单独驾驶和并行行驶目的地会更快。 在短期内这可能会更快,但是考虑到所有因素,时间可能不是这里最重要的因素。 当涉及计算机程序时,使用一辆汽车并确保在两次旅程结束时无凹痕可能是一个更为重要的因素。 这就是为什么我们喜欢结对编程的原因。

整理和任务自动化 (Linting and Task Automation)

If you have to drive alone on that long trip, you can still make your journey safer by relying on tools. A map is a tool. The GPS is a better tool. Cruise control is another tool.

如果您必须在长途旅行中独自开车,您仍然可以依靠工具来使旅途更安全。 地图是一种工具。 GPS是更好的工具。 巡航控制是另一种工具。

Tools that automatically warn you if you do something wrong while driving are similar to linting tools for coding. In JavaScript, the best linting tool today is ESLint. It will warn you about so many wrong things you should not be doing while coding. Best of all, it can do that even before you run your program.

如果您在开车时做错了事,会自动警告您的工具类似于整理工具。 在JavaScript中,当今最好的整理工具是ESLint。 它会警告您在编码时不应该执行的许多错误操作。 最棒的是,它甚至可以在运行程序之前完成。

Examples of tools that warn you while you are driving are evolving in modern cars. Cars can now warn you when you cross a lane line unexpectedly, or when you try to turn or change a lane while not seeing that hidden car in your blind spot. Additionally, they warn you when you drive over the speed limit, or when you are about to hit something while trying to park in a tight spot.

在您开车时会警告您的工具示例正在不断发展,现代汽车已在不断发展。 现在,当您意外越过车道线时,或者当您尝试转弯或更改车道而又看不到您的盲区时,汽车会发出警告。 此外,当您开车超过限速时,或者当您试图在狭窄的地方停车时,如果碰到某些东西,他们会警告您。

Linting tools also evolve to provide more accurate and helpful warnings. ESlint always surprises me with very accurate warnings. Additionally, its default recommendations are getting better with each upgrade.

整理工具也不断发展,可以提供更准确和有用的警告。 ESlint总是以非常准确的警告使我感到惊讶。 此外,每次升级后,它的默认建议都会越来越好。

Another analogy that I love in modern cars is automation. Any task that you repeat often should be automated once its purpose and value are clear. Instead of restarting that program every time you save the file, have a monitor process that automates that. Rather than running a format command on your code before you share it with others, have a command that automatically does that every time you commit your code to source control.

我在现代汽车中喜欢的另一个类比是自动化。 一旦明确其目的和价值,您经常重复执行的任何任务都应自动执行。 不必在每次保存文件时都重新启动该程序,而要有一个自动执行该操作的监视程序。 与其在与他人共享之前在代码上运行格式命令,不如在每次将代码提交到源代码管理时自动执行该命令。

Modern cars automate so many things as well. The obvious example here is adaptive cruise control, but other subtle examples include automatic windshield wipers and automatic high beams at night (my favorite!).

现代汽车还可以自动完成很多事情。 这里最明显的例子是自适应巡航控制,但其他细微的例子包括自动挡风玻璃刮水器和夜间自动远光灯(我最喜欢!)。

命令式与声明式编程 (Imperative vs Declarative Programming)

When you need to do something, there is always the what and the how aspects of it. What exactly needs to be done and how do we do it.

当您需要做某事时,总会有它的内容方式 。 到底需要做什么以及我们如何做。

Imperative programming is about the how. Declarative programming is about the what.

命令式编程是关于如何进行的 。 声明式编程是关于what的

What? How? And why should you care?

什么? 怎么样? 为什么你要在乎?

An imperative approach represents a list of steps. Do this first, then do that, and after that do something else. For example: Go over a list of numbers one by one and for every one add its value to a running sum.

命令式方法代表了一系列步骤。 首先执行此操作,然后执行该操作,然后再执行其他操作。 例如: 逐一浏览数字列表,然后将每个数字的值加到连续的总和上。

A declarative approach represents what we have and what we need. For example: We have a list of numbers and we need the sum of those numbers. The imperative language is closer to the computers of today because they only know how to execute instructions. The declarative language is closer to how we think and command. Get it done, please. Somehow!

声明式方法代表了我们所拥有的和我们所需要的。 例如: 我们有一个数字列表,我们需要这些数字的总和。 命令式语言更接近当今的计算机,因为它们只知道如何执行指令。 声明性语言更接近我们的思维和命令方式。 请完成它。 不知何故!

The good news is computer languages have evolved. Computer languages offer declarative ways to do the needed imperative computer instructions. Just as cars have evolved from manual stick shift into automatic and self-driving ones!

好消息是计算机语言已经发展。 计算机语言提供了声明性的方式来执行所需的命令式计算机指令。 就像汽车已经从手动换挡转变为自动和自动驾驶一样!

Imperative programming is like driving a stick shift car. You need to do manual steps (press the clutch, depress it slowly, change gears incrementally, etc). Declarative programming is like driving an automatic car — you just specify the “what”: Park or Drive.

命令式编程就像驾驶变速杆汽车。 您需要执行手动步骤(踩下离合器,缓慢踩下离合器,逐步换档等)。 声明式编程就像驾驶自动汽车一样-您只需指定“ what”:停车还是开车。

You cannot program declaratively unless you have the tools that enable you to do so. While you can imperatively drive an automatic car (by switching to manual mode) you cannot declaratively drive a stick shift car. If all you have is a stick shift car, imperative programming is your only obvious choice. This is unless you take the time to install an automatic gear shifter, which might be worth it in the long term. If you can afford a new car, you will probably go with an automatic one unless you are that true nerd who still likes to program with Assembly!

除非您拥有使您能够进行声明式编程的工具,否则您不能进行声明式编程。 虽然您可以强制性地驾驶自动驾驶汽车(通过切换至手动模式),但不能声明性地驾驶变速杆汽车。 如果您只有挡车,命令式编程是您唯一的明显选择。 除非您花时间安装自动换档器,否则从长远来看这是值得的。 如果您买得起新车,除非您是仍然喜欢使用Assembly编程的真正书呆子,否则您可能会选择自动上车!

Assembly is the original true imperative low-level computer language with pure instructions that directly translate into machine code.

汇编 是真正的命令式底层计算机语言,其纯指令直接转换为机器代码。

Note that imperative programming might produce faster programs. Additionally, declarative programming requires less effort from you. In general, it will also require less effort to be maintained. Coding does not have to be one way or the other. Any non-trivial computer program will most likely have a little bit of both approaches. Also, knowing how to code declaratively is great, but it does not mean that you do not need to learn the imperative ways as well. You should simply be confident using both.

请注意,命令式编程可能会生成更快的程序。 此外,声明式编程所需的精力更少。 通常,也将需要较少的维护工作。 编码不一定是一种方式。 任何不平凡的计算机程序都很有可能同时使用这两种方法。 同样,知道如何以声明方式进行编码也很棒,但这并不意味着您也不需要学习命令式方法。 您应该只是自信地使用两者。

Tools that enable you to program declaratively evolve into better and faster ways to get you where you are heading. The ultimate declarative experience with modern cars is the self-driving ones. The “what” becomes the destination and the car will do the rest. This is somehow, probably, the future of programming as well. We will have programs that understand all goals and they can just work their magic to generate logic to get us to those goals.

使您能够以声明方式进行编程的工具会演变成越来越快的方法,从而使您到达目的地。 现代汽车的最终声明性体验是自动驾驶汽车。 “什么”成为目的地,汽车将完成其余的工作。 这也许也是编程的未来。 我们将拥有能够理解所有目标的程序,他们可以发挥自己的魔力来生成使我们达到这些目标的逻辑。

What is your favorite analogy? Let me know in the responses section below.

您最喜欢的类比是什么? 在下面的回复部分中告诉我。

Thanks for reading!

谢谢阅读!

翻译自: https://www.freecodecamp.org/news/hard-coding-concepts-explained-with-simple-real-life-analogies-280635e98e37/

工厂用抽象类比接口

工厂用抽象类比接口_用简单的现实类比解释硬编码概念相关推荐

  1. 详解设计模式之工厂模式(简单工厂+工厂方法+抽象工厂)

    园子里关于23种设计模式的博文已经可以说是成千上万.车载斗量.屯街塞巷.不计其数.数不胜数.摩肩接踵.汗牛充栋.车水马龙.门庭若市.琳琅满目直至让人眼花缭乱了.在这样的大环境下之所以来写设计模式类的博 ...

  2. 设计模式--简单工厂VS工厂VS抽象工厂

    前几天我一直在准备大学毕业生,始终绑起来,如今,终于有时间去学习设计模式.我们研究今天的话题是植物三口之家的设计模式的控制--简单工厂VS工厂VS抽象工厂. 经过细心推敲,我们不难得出:工厂模式是简单 ...

  3. 创建型模式:工厂模式(简单工厂+工厂方法+抽象工厂)

    一.引子 话说十年前,有一个爆发户,他家有三辆汽车(Benz(奔驰).Bmw(宝马).Audi(奥迪)),还雇了司机为他开车.不过,爆发户坐车时总是这样:上Benz车后跟司机说"开奔驰车!& ...

  4. 详解设计模式之工厂模式(简单工厂+工厂方法+抽象工厂) v阅读目录

    1楼留头头大神:http://www.cnblogs.com/toutou/p/4899388.html v阅读目录 v写在前面 v简单工厂模式 v工厂方法模式 v抽象工厂模式 v博客总结 v博客前言 ...

  5. C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)

    今天开始这个系列之前,心里有些恐慌,毕竟园子里的高手关于设计模式的经典文章很多很多,特别是大侠李会军.吕震宇 老师的文章更是堪称经典.他们的文笔如行云流水,例子活泼生动,讲解深入浅出.好在他们都是用C ...

  6. 从简单工厂到抽象工厂

    最近在画机房收费系统的图,登陆部分实现了两次一次是三层,一次是加设计模式. 都知道访问数据库的连接用的是抽象工厂加放射,我先用这种方法实现后,又改为简单工厂啦,发现简单工厂实现比抽象工厂简单很多.决定 ...

  7. 简单工厂、工厂、抽象工厂

    简单工厂模式:专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类.它又称为静态工厂方法模式,属于类的创建型模式. 简单工厂模式的实质是由一个工厂类根据传入的参数,动态决定应该创建哪 ...

  8. 简单工厂 工厂方法 抽象工厂

    [找到一篇好文章] 作者:海粟007 原文址:http://www.cnblogs.com/Seasky/archive/2009/04/28/1385609.html 今天开始这个系列之前,心里有些 ...

  9. 简单工厂和抽象工厂有什么区别?

    简单工厂和抽象工厂有什么区别? 简单工厂模式 是由一个工厂对象创建产品实例,简单工厂模式的工厂类一般是使用静态方法,通过不同的参数的创建不同的对象实例 可以生产结构中的任意产品,不能增加新的产品 抽象 ...

最新文章

  1. Debug的T命令在执行修改寄存器SS 的指令时,下一条指令也紧接着被执行。
  2. SAP S4 OP/Cloud大乱斗
  3. Java基础-我所理解的泛型
  4. 编程软件python中的if用法-总结Python编程中函数的使用要点
  5. 从B站到咪咕圈圈,看汉服「出圈」与年轻人「入圈」
  6. CSSbackground的详细使用
  7. Jmeter添加压力机
  8. python写网络调试助手_Qt开源作品4-网络调试助手
  9. js for循环给object数组赋值
  10. android adjust,【报Bug】安卓 adjust-position设置为false 页面依然被顶起 ios是好的
  11. (转)PJAX的实现与应用
  12. SSH+Oracle10G抛Disabling contextual LOB creation as createClob() m
  13. python模拟足球_使用K-Means算法划分亚洲国家的三个足球梯队
  14. java网络学习之 ssh 协议学习总结
  15. 【ModelScope】KAN-TTS搭建SAMBERT个性化语音合成开发环境
  16. 如何破解自如的反爬机制
  17. 别忘了看,今年中秋月亮“瘦”了!网友扎心了:我还没瘦…
  18. php家居门户源码,家居装修门户模板源码discuz模板 php家居装修网论坛源码
  19. 文件夹只读属性不能更改如何去除
  20. Exynos_4412——IIC总线概述

热门文章

  1. Mysql排序后显示排序序号
  2. jQuery绑定事件的三种常见方式(bind、one、【change、click、keydown、hover】)
  3. vue写一个通用的toast弹窗 toast 弹窗 提示
  4. 微信小程序swiper组件宽高自适应方法
  5. [微信小程序]滚动选择器
  6. Objective-C 自动生成文档工具:appledoc
  7. [Python_7] Python Socket 编程
  8. tf.nn.relu
  9. nginx技术(2)nginx的配置详解
  10. Console-算法-冒泡排序法|倒水法