Kõva kodeerimise mõisted, mida on seletatud lihtsate tegeliku elu analoogiatega

Kuidas seletada 5-aastasele lapsele kodeerimise mõisteid nagu voogud, lubadused, kiilumine ja deklaratiivne programmeerimine

Mulle meeldib mõelda mõistete kodeerimisele, võrreldes neid tuttavate asjadega, mida me elus teame. Kodeerimiskontseptsioonide kohta on nii palju analoogiaid. Mõned neist on head, teised aga segadust tekitavad peamiselt seetõttu, et nad keskenduvad mõiste osalistele aspektidele, eirates paljusid teisi. See artikkel võtab kokku mõned analoogiad, mis minu arvates sobivad kõige paremini kodeerimiskontseptsioonidega.

Värskendus: see artikkel on nüüd osa minu raamatust “Professionaalne programmeerija”. Lugege selle sisu värskendatud versiooni ja lisateavet programmeerimise kohta aadressil jscomplete.com/pro-programmer .

Alustan lihtsate mõistetega ja lähen raskemate juurde. Alustame enda kodeerimisest. Kodeerimist saab võrrelda toiduvalmistamise retseptide kirjutamisega. Selle analoogia retsept on programm ja kokk on arvuti. Retsept on kokkade juhiste loetelu, mida peab järgima, ja programm on loetelu juhistest, mida arvuti peab täitma.

See on väga lihtne analoogia, arvestades, et retsept on kirjutatud inimkeeles ja programm on kirjutatud arvutikeeles ning need on väga erinevad keeled (välja arvatud juhul, kui teie retseptidel on sulgemisi ja lubadusi!). Samuti pole retseptis palju ootamatuid asju planeerida, samal ajal kui arvutiprogrammil on palju. Hoolimata lihtsusest on see hea viis näidata, kuidas arvuti juhiste loendit järjest täidab. Samuti näitab see, kus üks käsurida saab kasutada mis tahes tulemust eelnevate käsuridade käivitamisel.

Mõnes retseptis on isegi if-laused: kui küpsetate 2, 4 või 8! Mõnes retseptis on aasad: jätkake segu segamist kuni…

Mulle meeldib see analoogia ka kõigi valmis esemete ja tööriistade tõttu, mida saate oma retseptides kasutada - näiteks koogisegu, mida saate kasutada koogikeste valmistamiseks, ja see spetsiaalse kujuga pann, mis muudab koogikeste loomise palju lihtsamaks.

Valmis esemete ja tööriistade kasutamine on nagu teiste kirjutatud koodipaketi lisamine ja kasutamine teie enda koodis.

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

NPM on paketi haldur Node.js-le , mis on väga populaarne raamistik JavaScripti rakenduste kirjutamiseks. Selles analoogias on Node.js nagu köök ise. See võimaldab teil oma retseptides ridu täita, kasutades sisseehitatud mooduleid nagu teie ahi ja valamu.

Ebatervislikust toidust rääkides on see järgmine analoog kodeerimise õppimiseks ja seda võrreldakse söömisharjumustega. MULLE ARMASTAB seda analoogiat ja seda, mida see edasi annab, sest see aitab mul koodi õppimise teekonnal kursil püsida. Minu jaoks sai see alguse keskkoolist ja kestab seni, kuni mu aju saavutab viimase juhise: sure ();

Kodeerimise õppimine

Kodeerimise õppimine on nagu katse kaalust alla võtta. See analoogia kehtib tõeliselt kõige õppimise kohta, kuid kodeerimise õppimine on siin eriline vaste.

“Kaalu kaotamine” on negatiivne termin. Me peaksime seda tõesti nimetama "Tervise saamine". Selles mõttes on see väga võrreldav „Teadmiste hankimisega”. Teie käsutuses olevad haridusressursid on nagu teie toiduvalikud. Mõni on lihtsalt okei, mõni on suurepärane ja mõni on teile täiesti halb. Tervislik toitumine ja liikumine on kaks peamist tegevust, mis aitavad teil tervist saada. Samamoodi on head haridusressursside tarbimine ja käsitsi kodeerimise harjutamine kaks peamist tegevust, mis aitavad teil häid kodeerimisteadmisi saada.

Kuidas siis õppida "tervislikku"? Kui pühendute tervislikule toitumisele, kasutate selliseid filtreid nagu orgaanilised , kohalikud , madala rasvasisaldusega , rohuga toidetud ja mitte-GMO-d. Tervislike haridusressurssidega on täpselt nii, et need sildid pole veel nii selged. Loodan, et ka hariduslikel ressurssidel on kunagi kontrollitavad ja asjakohased sildid. Võib-olla sildid nagu „mitte sponsoreeritud”, „turunduse keelamine”, „ekspertide poolt heaks kiidetud”, „tihedalt redigeeritud” ja „lohed ette”.

Kuid sisu järgi filtreerimise asemel saate hõlpsalt heade kaubamärkide järgi filtreerida. Ma teen seda ka toiduga. Ma tean ja usaldan mõnda kaubamärki ja kasutan enamasti neid. See on lihtsam. Haridusressursside olemasolul on mõned kaubamärgid (väljaanded ja inimesed), mida peaksite lihtsalt kogu aeg jälgima.

Pärast teadmiste kogumise filtreerimist ainult headele ressurssidele peate lihtsalt trenni tegema! Harjutage kõike, mida õpite, kuid mitte ainult tehes uuesti täpselt seda, mida õppisite. Samuti esitage endale väljakutse, et teete õpitud teemadel midagi veidi erinevat. Kui veab, siis jäädki kinni! Siis õpid püsivalt midagi muud, kui sul lahti jääb.

Harjutus on mõeldud nii kehale kui vaimule.

Muutujad

Muutujaid kasutatakse arvutiprogrammides andmete hoidmiseks . See on väga lihtsustatud väide ja on paljude meetmete järgi lihtsalt vale.

Muutujad ei hoia andmeid. Nad lihtsalt osutavad sellele. Andmeid hoitakse arvuti mälus. Muutujaid saate võrrelda e-kirjade (või märkmete või failide) asetatud siltidega.

Kõik selle artikli koodinäidised on kirjutatud JavaScripti abil. JavaScripti on väga lihtne õppida arvutikeelt.

Gmailis on silt osutus e-kirjale või meilide loendile. Paljud sildid võivad osutada samale e-posti aadressile. See sarnaneb teise muutuja määramisega olemasolevale muutujale:

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

Nii töö kui ka oluline on nüüd sildid, mis osutavad täpselt samale meilide loendile.

Mõned muutujad tähistavad pidevaid viiteid . Neid ei saa muuta. See on nagu Gmaili silt „ Saadetud ”. Ehkki me saame ülaltoodud töösilti muuta ja panna selle osutama teisele meilide loendile, ei saa me saadetud silti muuta. Saadetud silti ei saa suunata teise meilide loendi juurde. Saate selle osutada ainult rohkematele meilidele.

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

Vead ja erandid

Programmeerija teadmised on suures osas seotud vigadega toimetulekuga. Asjatundlikud programmeerijad armastavad vigu, sest nende jaoks tähendavad vead edasiminekut.

Mõnikord eeldame, et näeme neid suurepäraseid punaseid sõnumeid, ja kui me seda ei tee, teame, et kood on lihtsalt vale!

Mulle meeldib fraas “ kuula oma koodi”, sest arvan, et kood areneb meiega vigade abil suheldes.

See on täpselt nagu laste kasvatamine.

Kõige olulisem lapsevanemaks olemise mõiste, mida ma praktikas mõistsin, on see, kuidas lapsed suhtuvad valesti käitudes. Seda seetõttu, et neil pole veel loogilist aju. Ma arvan, et programmid teevad täpselt sama asja. Nad suhtlevad ka valesti käitudes (tekitades vigu), kuna programmid pole täiesti loogilised. Teie ülesanne programmeerijana on lisada koodi juurde loogikat, et käsitleda juhtumeid, mis algselt tõid vigu. See on täpselt nii, nagu vanema ülesanne on õpetada valesti käituvale lapsele, mis on selle halva käitumisega valesti ja mida järgmine kord teisiti teha.

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);}

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.

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.

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.

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.

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.

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.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 stands for Last In First Out and FIFO stands for First In First Out.

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.

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.

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.

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.

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.

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.

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.

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? 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.

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!

Assemblyis 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.

Tööriistad, mis võimaldavad teil deklaratiivselt programmeerida, arenevad paremateks ja kiiremateks viisideks, kuidas teid suunduda. Kaasaegsete autode ülim deklaratiivne kogemus on isejuhtivad. “Mis” saab sihtkohaks ja ülejäänud osa teeb auto. See on kuidagi ilmselt ka programmeerimise tulevik. Meil on programme, mis mõistavad kõiki eesmärke ja nad saavad lihtsalt töötada oma võluväel, et luua loogika, mis meid nende eesmärkideni viiks.

Mis on teie lemmik analoogia? Andke mulle sellest teada allpool olevast vastuste jaotisest.

Täname lugemast!