Programming 101 with "Uncle Bob"

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] [Music] welcome to the programming primer I presume you're here because you want to learn how to program a computer let me tell you why that's a very good idea computer programs software it's everywhere of course it's in your laptop computer or your desktop computer or your phone or your tablet but it's also everywhere else it surrounds you I mean it's in this inner come it's in this dumb light switch it's in the coffee maker the toaster oven the range the oven the microwave oven the refrigerator my thermostats the washing machine and dryer my security system my window shades television remote controls television over there and all the devices underneath it that motion controller that's smuggle on my furnaces the humidistat the humidifiers this whatever it is my Bluetooth speaker this microphone that I use has software in it my electronic drums that whiteboard has software in it the camera that you're looking through that printer my key fobs [Music] and there's a ton of softer in these cars I mean they're softer inside the engines that monitors the engines and if you think about the entertainment centers in here and the GPS systems in here there's just gobs of software for that but there's more these cars all have little little sensors in them these are ultrasonic sensors that can sense when other things are nearby and now over here there's a front looking radar and a camera that looks at the road and it can see lane markings this code this car knows where it is in the highway lane system and it can warn you it can tell you if you're drifting over a lane it'll tug on the steering wheel there's software in there that does on the steering wheel there's software all through this stuff my point is that software is everywhere and it completely dominates our lives I mean think about it you probably interact with software in one form or another every second of your waking life and some of us even have software that monitors our sleep and with all that software surrounding us we've barely scratched the surface think about what might have software in it ten years from now every light switch every wall outlet every light bulb every door lock every pen or pencil how about your pair of glasses or a stapler or a carving knife what about the hot water dispenser what about all the faucets and the toilets and the shower the bed that lamps all that stuff could have software in it and we haven't even begun to talk about household robots if this car can detect its lane position and tug on the steering wheel to warn you if you're crossing the lane how long before it actually just drives itself and think about it what if you could tell your car to drive to the store to pick up the groceries that you ordered online while you stayed at home working in your home office writing software for your employer I think you get the picture there's a lot of software already out there and it all needs to be maintained and improved and then there's a lot more software that needs to be written we don't have nearly enough people to do it over the last half century the number of programmers in the world has doubled every five years or so today there are tens of millions of programmers and it's not enough I believe that the number of programmers in the world will continue to double every five years for several more decades in fact I think it's pretty reasonable to believe that computer programming could become both the most popular and the most populous career so this is a good time to be interested in programming because if you know how to program and you can do it well then you're going to have a rewarding challenging high-paying career but it's not really about the money or the career Oh believe me that helps yeah but programming is about something else programming is about passion you've got to love it you really can't do this kind of work unless you enjoy of a hell out of us here's a dirty little secret about programmers if they didn't pay us to write the code we pay to write the code don't tell anybody that's a secret but there's a lot of truth in it a good programmer loves to program do you love to program that's what you're going to find out as you follow along with this course what we do in this course is going to challenge you and it will puzzle you and it will frustrate you until you are pounding your fists against the side of your head you will believe that you have never done anything this difficult you'll be enraged that the simplest thing seems so hard and yet if you stick with it you just might find that you love it like I do and then like me you want to do it for the rest of your life [Music] so what is a computer well nowadays if you ask that question people would answer it by pointing at their laptop or or their smartphone or their iPad or maybe their Apple watch or something like that and and while it's true that all of those things are computers there's a much simpler answer let me show you this little switch and that overhead light and the wiring inside the walls here form the elements of a very simple computer you might not think of a light switch as a computer but it is one and I'll prove it to you first of all there's an input device the switch there's an output device the light there is memory the switch remembers what position it's in and there is control logic within the wires of the walls input/output memory logic and control these are the elements that make up a computer now the logic of this computer is fairly simple if these switches up then the light is on if the switch is down the light is off up on down oh my god light off so here's a little model of that behavior written as a computer program right here and notice over here I've actually got a little light bulb and a switch and if these switches down then the light is off but if the switches up then the light is on so you can see that the switch and the light behave just like they should now let's look at the program here is the program that controls this switch in this light there's a few things you should ignore ignore this line entirely what we'll come to that later ignore parentheses ignore dots ignore semicolons ignore the word void that's all coming later it's not important right now what is important is this if switch a is up why did I say switch a well I named this switch a so if switch a is up then the light is on otherwise the light is off that is the logic that controls this little program right here and this is the program that is running when I do this so there's the logic that codes not very hard to understand is it I mean it reads very nicely if the switch is up the light is on otherwise the lights off but here's the thing everything in software is just that simple you are never going to find a concept in software that is any more complicated than fact that's not to say that there aren't complicated problems in software believe me there are it's just that all of those complicated problems can always be broken down into statements that are as simple as if up then unn always to give you an example of how complexities arise in such simple systems look over here at this switch this switch it's not the same switches before that switch is over there this switch is by a different door by the hobby room door but notice this switch controls the overhead light too but this which seems to use different control logic because look the switch is down but the light is on and when we raise the switch the light goes off down on up off so here's our program again except this time there are two switches a and B and switch a works as you would expect just like it did before and that's because the switch a rule is still here but switch B doesn't do anything at all and that's because there's no rule over here for switch B so let's add the rule for switch be the way we stated it if switch B dot is up well then we'll turn the light off remember it's the opposite otherwise then we'll turn the light on now if we run this program I always see that switch B is down and the light is on and if we're a switch B the light goes off so that's working exactly the way it's supposed to I guess our rule just working um are we done well you see programmers have to be careful about saying that they're done because it's possible to break one rule when you add another one and that's really what we've done here when we added the rule for switch B we've broken the rule for switch a which I can show you by demonstrating that switch a doesn't do anything at all why is switch a not working when switch a's rule is sitting right here the answer to that is that the computer executes these rules in order it first executes the rule for switch a because switch a is the first rule here and then it executes the rule for switch B and look at what happens in the rule for switch B if B is up the light will be off if B is down the light will be on this completely erases the effect of switch a switch a even though switch a is actually happening this rule is getting executed this rule here switch B's rule overrides it if you could look very carefully you would see that light flash for an instant when I turned it on because this statement is getting executed but switch switch B's statement here comes along so fast that it turns the light off before you can even see it if we were to take these two rules and change their order so that switch B's rule is first and switch AIDS rule is second well notice what happens then switch a works switch B doesn't do anything it's the rule that executes last that you get to see working so clearly there's something wrong with our logic there must be something about this problem that we don't understand yet let's go back to the switches and take a closer look okay so switch a is up and the lights on that's right and switch B is down and the light is on that's right okay so now let's change the state of switch a switch a Goes Down and the lights off and that's right but look at switch B switch B is down and the light is off that's wrong well it can't be wrong because that's the way the system works but it's not the way we thought it worked I guess these two switches depend upon each other it's not as simple as up on down off right this is more complicated than that I think we're gonna have to write it down okay so I've made a table of the four possible switch positions they can both be up they can both be down or they can be the opposite of each other so there's four possible States now let's go out there and write down what happens to the light when we put the switch in these four positions all right so down up down up is unn and how about up up up up is off okay so now up down that's on and down down and that's off so if the two switches are the same either both up or both down then the light is off but if the two switches are different then the light is on this little computer of ours is actually kind of smart it can compare the state of those two switches and if the two switches aren't the same then it turns the light on but if the two switches are the same it turns the light off and think about what this means it means that anytime anybody changes just one switch the state of the light changes so you never have to hunt for the right switch you just find your switch and you don't it doesn't matter boom you just change it this is really kind of smart so let's write this code this is the old bad code let's get rid of that now the new code I think it looks like this if switch a that is up and this is how we do and right there and switch B dot is up then well that means that the light should go on and also if switch a dot is down and switch B is down then the light should be on and if not the Malad should be off hmm and how do we get the light to turn off let's do this let's say light off so first we'll turn the light off and then we'll turn it on again if it ought to be on and that should you switch be there and see over to that blank line cuz I don't like extra blank lines and let's see if this works okay they're both down so it's on that turned it off that turned it on that turned it off I tend to know how that works that's exactly what it's supposed to be so this is the logic here that's just the logic we want although I kind of hate turning it off and then turn it on again and I wonder if we can do better and I think we can let's let's do this let's say or that's how you do an or right there okay so now we can say if switch a is up and switch B is up or switch a is down as which B is down then the light should be on and else the light should be not off let's try that one okay oh that seems to work yes okay that works just like it should but why did it work notice that the ends seem to take precedence over the or for example I say switch a is up and switch B is up or so it's a is down and switch B is down notice the pause and the way I said or a--they the end seemed to take place before the ORS let me put parentheses in to accentuate that a little bit this is how we make sure that things happen first in most languages we put parentheses in and now you can see that that grouping right there and that grouping right there will both happen before that so the ends take place before the ORS in this case because of the parentheses now it just so happens that in the language Java ends take place before ORS anyway that's just a natural consequence of the language the way the language is written so I don't need those parentheses although it might be polite to the poor reader to leave them in rather than depending on the natural precedence of the language so maybe I'll just leave them in that way then let's run it again make sure I didn't break anything yeah that's the way it works okay is this the best we can do well remember what we said we said that if the two switches are in the same position the light should be on so either both down or both up so what if we did this instead of this horrible logical expression there what if we said if switch a state equals switch B dot state I wonder if that will work oh yeah that works too look at that that's much simpler if the two switches states are equal then we turn the light on otherwise we turn the light off that's cool [Music] earlier we saw some code on the screen that looked like this if switch a is up and switch B is up what does that word and mean now I know that seems obvious but one of the things you learn pretty quickly about computer programming is that it's the obvious things that get you into trouble so what we're going to have to do is be as precise as possible one of the most important things about programming computers is to be completely precise and that means we're going to have to understand the definitions of words like and and or thoroughly and completely so what does and mean this end right there what does that mean so let's look at the sentence again notice that the + symbol connects two clauses here's the first Clause switch a is up and the second Clause switch B is up these two clauses are special because they can only have two results true or false a clause that can only have those two results true or false is called a boolean clause and the true or the false value that it can have is called a boolean value it's called boolean after a man named George Boole who worked out an entire mathematics of true and false that we're gonna get to that later anyway here we've got our and symbol connecting two boolean values now what does and mean well here is a truth table that describes what and means and notice that this truth table has one output a and B it has two inputs a and B these two inputs are called boolean variables a and B are boolean variables because they can only have two values true or false the operation a and B is a boolean operation because it can have only two results true or false you see there's false and just true the value of the and operation is true only if both a and B are true every other combination of a and B results in a false value for a and B so in order to be true a and B have to be true let's see that in action let's replace this expression here with switch a is up and switch B dot is up and now let's run this and we should notice that the light will come on only if both a and B are up this matches our truth table perfectly what you have just learned is very important so hold it in your mind don't let it slip away a big part of computer programming is the understanding and manipulation of boolean variables variables that have only two values true and false so remember all of this in fact you might want to write it down we also saw a statement that looked like this if switch a is up and switch B is up or switch a is down and switch B is down what is the meaning of the word or in that statement and remember we have to be completely precise the word or R seems to separate two clauses in parenthesis and both of those clause azar and clauses and that means of course that they are boolean clauses therefore the word or is connecting two boolean values here's the truth table for a or B this is the or operation here and notice that the value of a or B is false only if both a and B are false otherwise if either A or B or both are true then the value of a or B is true so the value of a or B is true if a or B or both are true let's see this in action as well I'll just change this and here to an or and we'll run this program and now if either switch is up the light will be on and if both switches are up the light will be on once again this matches our truth table for or perfectly these two truth tables are important for you to memorize because as a programmer you're going to encounter the logical operations of and and or over and over and over again and now let me show you one more very important logical operation the logical operation called knot this is the symbol for not an exclamation mark in our language sometimes that mark is pronounced bang here is the truth table for the not operation the not operation has a single input a and a single output not a if a is true then not a is false if a is false then not a is true we sometimes refer to this as inversion once again let's see that in action we're gonna wire up our little program here so that it uses the inversion of switch a is up and we do that inversion with this exclamation mark that's pronounced not so if not switch a is up and if we run this program we will see that if switch a is down the light is on if switch a is up the light is off so that's the inversion of switch a and notice which B does nothing because we have nothing wired up for switch B and or and not these are the three fundamental boolean operations everything a computer does is in fact a combination of these three operations all the math a computer can do all the addition subtraction multiplication and division are just combinations of ands ORS and nots you may find that hard to believe but I'll prove it to you a little bit later but for now let's see another little bit of boolean magic now look here at this truth table for the and operation you'll recognize it as and because the only true output is the one with two true inputs every other output is false that's the and operation so now we're going to invert every true and false in this table we will invert the two inputs we will invert the output watch as I do this the new value will be in red this will be a true this will be a true that will be a true this will be a false this will be a true that will be a true this will be a true and that will be a false this will be a true this will be a false this will be a false this will be a and now look what we have compared this table to that table that's the truth table for or and notice true and true is true false and true is true true and false is true false and false is false that is the truth table for or by inverting the inputs and the output we change an end into an or okay now let's see this in action I'm going to start with that not again and then I'm going to take everything and put it in parenthesis so I'm gonna do a bunch of stuff in parenthesis here and then I'm going Verte it and what I'm gonna put in parentheses is nut swich a dot is up and not switch B dot is up and I'm missing a couple of parenthesis there and there and day let's see I need one more here good now let's see if we can read this properly got lots of parentheses in here but we've got nuts which a is up and nuts which B is up and then we're going to invert that so it's the knot of the nuts which a is up and knots which B is up I know a lot of knots but let's um let's run it and oh my it goes on if B is up it goes on if a is up and it goes on if both is up that's the or operation isn't it if you invert the inputs of an end and then invert the output of that and you get in for a or B and now let's do the same thing to the truth table for or we're going to invert all of the inputs and the output so that's going to be a true and a true and a true and this is going to be a false and a true and a false and this is going to be a true and a false set of false and this is going to be a full set of false and a false and what do we wind up with we wind up with the truth table for and if you invert the inputs and the output of or you get end and let's see that in action too I'll just change this and to an or everything else remains the same and now when we run this we should see that the light does not go on unless both a and B are on if you invert the inputs of an over and then you invert the output you get an and the fact that you can change and into or by inverting the inputs and the output and the fact that you can change or into and by inverting the inputs and the output our facts that you are going to have to commit to memory because every programmer needs to know how to use these facts intuitively these facts are known as de Morgan's law after Augustus de Morgan who discovered them in the 1800s and all of this logic these truth tables and laws are part of a mathematical discipline known as boolean algebra this is a topic we'll be returning to in another episode because mastery of this skill is important for all computer programmers [Music] but enough of this mathematical mumbo-jumbo because our light switch has a new wrinkle follow me all right so look it over here there's another light switch on that wall right by the stairs and if I flip it it turns the overhead lights off and if I flip it again it turns the overhead lights on there's not two switches that control this light there's three switches to control this light what is the logic for three switches controlling the light so let's write down that truth table [Music] whoa that's quite a table how are we going to write the code for this table well we could brute force our way through it like this I mean here are the the four expressions for the the light on part of the truth table so if switch a is down and switch B is down and switch C is up then the LED be on or if switch a is down switch B is up and switch C is down the light will be on or switch a is up switch B is down switch C is down the light will be on or switch a is up and switch B is up and switch C is up all of those will turn the light on otherwise the light goes off and I mean this works I mean every time you change a switch right it changes the light and that's the right behavior no matter what switch you go to it changes the state of the light whenever you toggle that switch so that is the right behavior but boy is that ugly code huh I mean you wouldn't want to have to read that for the rest of your life would you there must be something we can do to make it better and one thing you can do to make code better is to use some variables and some names here let me show you [Music] so this really cleans things up a lot just these three boolean variables here a B and C which are set to the state of the switches up state then you just use these logical expressions here and it works just fine this is the inversion of a so that would be if switch a is down and switch B is down and C is up or switch a is down B is up and C is down or switch a is up B is down C is down or a is up B is up seiza and this works just like before every time you toggle a switch it changes the state of the light so that's working perfectly and it's a lot prettier than before I mean never underestimate the power of some pleasant names but I bet we can do better still let's look at this truth table again because there's some obvious groupings that we might be able to take advantage of for example notice that the first four rows have a is being false and the second four rows have a as being true I betcha we can use some parentheses to group that together yes I think we can capture that grouping do you see how the not a and is present there and the not a and is present there and they're separated by an or operation here let's um let's bring these two up to the same line that's better now I think what we can do is we can use something called the distributive law of and over or you don't need to know that for the moment later on you will but what I'm gonna do here is I'm going to put parentheses around this and I'm going to get rid of the a and here the not a and there and so this will be not a and not being C or B and not C and if I did this correctly then it should behave as it did before which it does it's behaving just fine and I should be able to repeat this again here on the second line by bringing those up to the same line then I'll put a parenthesis there and another one here and just remove that a and there and if I did that correctly it should still work out fine and it looks like it does yes that's behaving properly so I mean that's a little better maybe not a lot better but it does expose something to the trained eye do you see this expression right here not B and C or B and not C that happens to be an operation that we call an exclusive or if you know it if you are trained in this then you would recognize that as an exclusive or here is the truth table for exclusive or notice that it looks just like an or operation except for the final row in the final row if both a and B are true then the result of exclusive-or is false and what that means is is that exclusive or will be true only if a and B are different but if a and B are the same that exclusive or is false this is another one of those ones you're gonna want to commit to memory every programmer has to be able to use exclusive wor intuitively now it just so happens that I've written an exclusive or function elsewhere and it goes by the name XOR so I'm going to replace this with a call to my XOR function my XOR function like so that does the same thing as that previous expression except it calls my XOR function and now if I run this I believe it will work as it did before oh yes it works just like it did before that's much better isn't it yeah except that we still have this ugly expression down here this whole if statement is asymmetrical and I I don't like things that are asymmetrical they bother me hmm so here's that expression we saw in our code not B and not C or B and C and if we create the truth table for that entire expression using B and C as our inputs we get true false false true now if you remember what XOR looks like XOR is the opposite of that fall's true true false so our expression here is the inverse of exclusive or it's not B XOR C and that actually is an operation that we call exclusive nor or X nor so this gives us the ability to clean things up a little bit so our ugly expression down here is the opposite of an X or it's an X nor which means we should just be able to say this there that's the not of the X or of B and C let's see if that works oh heavens mm well if I work just fine doesn't that every time you touch a switch it inverts that's very nice good um okay well gosh you should see something interesting here not a and something or a and not something you know what that is don't you that's her xor function so I think we can do this [Music] I wonder if that'll work it certainly does yeah I mean that's a lot better isn't it the three switches that is just the exclusive-or of switch a with the exclusive-or of switch b and c by now i hope i've convinced you that understanding those truth tables is both important and powerful I mean we took some pretty ugly code and by using those truth tables we reduced it down to something both simple and elegant if you didn't follow what we did or you don't think you understand it entirely go back and review it because we've got a lot more to do [Music] believe it or not there's another switch come on follow me it's way over here look at this way over here right by the guestroom door there is another switch that controls the overhead light and look I can go to the one by the hobby room door and if I turn the light off from this switch well then I can turn the light on from the switch by my office door and then I can go over here to the one by the stairs and then I can turn the lights off with that one this is cool isn't it so here's the truth table for the four switches and if you look carefully you'll see that there are 16 rows here because there are 16 possible combinations of 4 switches and if you analyze this truth table carefully you will find that if you change the state of just one switch you will invert the state of the light work through it if you'd like to prove that to yourself any single change from a true to a false will invert the state of the light now can you imagine writing this in code with all the ends and the oars and the knots here let me show you what that would look like yeah so this is pretty awful isn't it I mean look at that look it works let me show you I can run it and every time you touch the switch it inverts the light bulb and every single time and by the way now testing it is starting to get a little bit difficult because are you sure you're hitting all the switch combinations but yes it does work but look no programmer worth their salt would leave code looking like this it's awful there has to be a better solution and of course there is so look let's put that original free switch solution back in that was just the XOR of a time with the XOR of B and C there we go and that should work with a B and C but D doesn't do anything now there's a little pattern here isn't there could it really be as simple as that could could that be the solution let's see that looks like the solution oh my notice the nice little pattern there that's that's really nice isn't it do you see the value of learning these truth tables and logical operations intimately I mean without them we could have built that code out of long chains of ifs man's lures and knots but by applying those truth tables and understanding the logic we were able to reduce that down to a simple set of L statements a very manageable size bit of code and believe me when you're maintaining tens of thousands of lines of code you'll be grateful for any little help you can get I promise there are no more switches but I do have a question does that solution implemented by the switches out there address the actual need the need was to be able to control the light from any of the light switches so for example I might be walking down these stairs into a dark room and need to turn the lights on or perhaps I'm walking into my office and I need to turn the light off or maybe I'm walking out of the guest room into a dark room and I need to turn it on there are four switches in this room and from any one of those switches we need to be able to control the lights in this room and that's just what we have isn't it that's what this truth table proves if anybody changes the state of one switch the state of the light will change and that's just what this simple and elegant code achieves but is this what we really need for example imagine there are two people entering this room at the same time they can't see each other they both want to turn the light on and they both flip their respective switches at the same time what happens nothing nothing changes the lights don't go on because two switches have changed this is certainly not what we want the light should have turned us and notice that our program has the same behavior if if I throw two switches at once the light doesn't change State it might flicker a little bit if the two switches aren't thrown at exactly the same time but notice that when the two switches are thrown the state of the light remains the same now this is not what we want when two people change the switches at the same time we'd like the state of the light to change this is very typical of the kinds of problems that programmers face and the kinds of mistakes that programmers make when considering the behavior of a program it is easy to forget that time is often a factor in our case forgetting about time meant forgetting that two events could occur simultaneously how should we fix this the first problem is to detect when the light should change now the light should change when any change occurs to any number of the switches how are we going to detect that change when something changes it means its current state is different from some previous state so for example here's this switch first it was in this state now it's in that state notice it's all about time so to detect a change we're going to have to be able to compare the past to the present we're going to have to know what the state of the switches was and compare that to the state of the switches now and to do that we're going to have to use the computer's memory to save the past state of the switches we could do that like this look at this if statement here if if the position of a is not equal to the last position of a or the position of B is not equal to the last position of B or C not equal a C or D not equal see in other words if any of the switches have changed or even if several of the switches have changed then we change the state of the light we set thus the light state equal to not the light state we reverse the state of the light and this works I mean as you can see here I can I can click on the lights and it still behaves normally but I can also hit multiple switches at the same time and notice that the light changes properly and that's the behavior we're after but this is ugly this code here is ugly it's got four different variables in it it's checking for different things and what we'd really like here is something like this current switch state not equal to last switch State that's what we'd like to see in the code itself that's what the code meant before but this is what we'd like to see in our code and that means that we need a way to represent the state of all four switches in a single value that can be given a single name well that's actually not very hard to do let's imagine that the four switches represent the digits within a four digit number and if this switch is up we set that digit to a one we set the corresponding digit to a one if the switch is down we set the corresponding digit to a zero so for example if switch a were down well then we'd make that digit zero and if switch B were up well then we'd make that digit of one but if switch C were down with a mantich it would be a zero and if switch D were up well then that digit would be a one and that would give us the number 100 and one but if let's say a were up well then we'd want that to be a 1 and B let's say that's up so that's also a 1 and C is down that's a 0 and let's have D go down okay so now we've got the number 1100 that gives us a way to represent every every combination of the switches as a number you may be wondering why I would use a trick like this well the answer to that is that I want to find a simple way to represent the state of those four switches this is actually something that computer programmers do a lot of we spend a lot of time hunting for simplifying representations of complicated systems so I can construct my simple representation with this set of if statements right here I begin by setting the currents which state to 0 and then if a is up then I add a thousand to the currents which state so this will change the currents which state by a thousand if B is up then I add a hundred to the currents which state if C is up then I add 10 to the currents which state and if D is up I add 1 to the currents which state and then I print the currents which state here and I'll show you how this works it's fairly straightforward notice we begin with all the switches down and and down here at the bottom we see a zero that's because the currents which state is 0 Y is 0 well we set it to zero here and then since all the switches are down we never added anything but if I were to make switch a up the notice that down here again the currents which date is now equal to a thousand that's because if a is up then currents State gets an extra thousand added to it if I raise B over here you'll notice that now the the current switch date is eleven hundred because both a and B are up a thousand gets added to current switch date and hundred gets added to current switch state and when we print currents which state we see that eleven hundred and I can continue that ad infinitum I raise all of the switches and down here you see I've got eight one one one one which is good eleven hundred and eleven or I think bilbo baggins called that 11 the 11 anyway if I turn any of the switches off you'll see that the appropriate digit goes back to zero so I can easily make one thousand and one by having the the switch a and D up but B and C down and so on and this is just what we expect now we've got a single value current switch date that represents the position of all the switches so now all we have to do is remember that representation save it somewhere and then the next time we compute it we can compare the current representation to the old one and if they're different well then we know that the switches have changed and we can change the state of the light so that's pretty easy here let me get rid of that print statement cuz we don't need that anymore this if statement right here does exactly what we want if the currents which state is not equal to the last which state that means that somebody changed something and they may have changed more than one switch but if they did if something changed then we are going to invert the state of the light we are going to say that the light dot state the state of the light is equal to the inverse that's what that bang means remember the inverse of the current state of light and that should change this day the light and then lookie here we remember the current state of the switch in the last state of the switch last switch state equals current switch state that just takes this value here the current switch day then moves it into the last switch state so the next time we come through here we will remember what the last switch day was now that now look at this code again you don't need to understand everything about it there's some mysteries here that I'm sure you're wondering about all I care about right now is that you grasp the essence of what's going on this is where we gather up the state of the switches in two independent variables a B C and D and this is where we compute the representation of the switches into a single variable the current switch state and then we compare that the currents which state is not equal to the last switch state and if it is not then we invert the state of the light and then we remember the last switch day we move the current switch day to the last switch date now does this work well here I can run it and you'll see that it it works just like our XOR version did if anybody ever touches a switch then it inverts the state of the light but it's better than that because if someone were to touch two switches then notice that the state of the light inverts even though two switches are changing our X or version would not have done this so this is better although you may notice that it's just a little tricky getting both of those switches to change at the same time and sometimes they don't exactly change it precisely the same time but when they do when they change it exactly the same time then the state of the light in firts hmm it was pretty tricky to flip those switches at the same time wasn't it and the reason behind that is that the computer is very very fast it sees two events that are a thousandth of a second apart as two very separate events in fact a computer might look at two events that are a billionth of a second apart and think of them as separate whereas we humans we think of two events that occur within a second of each other as being simultaneous especially if those events are flipping a light switch think about what this means what we're trying to solve here is a human problem not a machine problem so when two humans enter this room and they flip their switches at the same time we want the lights to change at the same time is a human concept not a machine concept so let's see how our program behaves here I'm gonna start it running the light is currently off now I'm going to just try it here I mean it's working I'm going to change two lights at the same time but not quite at the same time now watch carefully what happens did you notice that the light flickered but it remains off now the two people tried to change the light and they flipped the switches at almost the same time and the end result is as the light didn't change State it flickered but it remained off this is this is not how we want this program to behave how are we going to fix this this is a timing problem isn't it it all comes down to timing we're going to have to measure the time between two events and if that time is too short we want to reject the second event if someone turns a light on and then someone else very quickly throws another switch we don't want that switch turning the light off so any event that comes within oh say a half a second of another event we want to reject so here's a timing diagram that shows this situation this is switch a it's down switch B down light is off that's how time begins now I'm a half a second later switch a goes up and that means that we should turn the light on so the light goes on then nothing happens for a full second right this time in here is a full second and then B goes up well that's long enough one second is long enough so we will accept that event and change the state of the light the light will now go off but now within the next half second there's another event switch a goes down and that's too short a time half a second is too short so we decide to reject that event and not change the state of the light okay so this is going to take just a little bit of extra code now the first code we'll look at is this here this Milly's function that returns the number of milliseconds since the program was started a millisecond is a thousandth of a second so current time will be set to the number of milliseconds since the program started if you don't know what this means that little int there that just means that current time is an integer so now that I have the current time I'm going to check to see if the state of the switch has changed and if it did then I'm going to check to see if it's been more than a half a second since the last time the state of the light changed and now how do I know that well I take the current time and I subtract from it the time that the light last changed and again this is in milliseconds so if I subtract those two and the result is greater than 500 milliseconds then I know that it's been more than a half a second since the state of the light changed so if it has been more than half a second then I change the state of void otherwise I don't I leave the state of the label but if it's been more than a half a second then I change the state of the light and then I remember the last time that I changed the state of the light I set last change time to current time now you might be wondering what happens the first time through what's the value of last change time the first time through well a little bit of secret code up here I set last change time equal to Millie's so that that would make sense now this code works if I hit switch a you see that it changes the state of the light if I hit switch B it changes it again if I hit them in very rapid succession you notice that it does change the state of the light which is correct and if I hit them in slower succession then it works properly the light the state of the light changes the state of the light will not change however if I hit them within a half a second bang-bang notice no change bang-bang no Ching bangbang so imagine that two people have entered the room in different parts of the room they can't see each other the light is off they both want the light to be on they both reach for the light switch and within a half a second bang-bang and the light is on even though two people switched the switch at slightly different times the light remains on that's the correct behavior for this program mmm I'm not so sure about that what would happen if someone turned the lights on and then very quickly realized that they'd rather have the lights off and turn them off within a half a second the lights wouldn't go off would they let's see this in operation imagine that I'm a 12 year old and I'm just walking into the room and I turn the lights on and then I forget something and I I realise that go back and so I turn the lights off real fast and here's what happens the lights stay on now twelve year old Amy says wait a minute that's not how that was supposed to work so I hit the switch again and of course the light goes off and I've isn't it and so to play with it I hit the switch three times and the second two times I flipped it didn't do anything and and so I just start flipping madly and I noticed that the light does not behave the way the switch is behaving the light will only change once every half second mom the lights down here just don't work right this violates a principle called the principle of least surprise when designing software for humans to use you don't want the humans to find the behavior of that software surprising in any way and not turning off a light when you flip a switch could be somewhat surprising how should we solve this problem well actually I think I'll let you work that out and at the end of the episode I'll show you how to get all set up so that you can run these programs on your local computer I'll give you a little hint though it's all about the timing and it's all about which switch you believe if the same switch changes within a half a second you should believe it it's only if a difference which changes within a half a second that you should ignore it by now you should have gotten the idea that designing software for humans to use is tricky business even a system as absurdly simple as light switches contains hidden complexities that can make the code get fairly complicated this is one of the reasons that computer programming is so much getting a program right is both challenging and very rewarding and getting software right involves having a good grasp of the basics so before we end this episode let's dive into one of those basics look at the way we calculated the representation of the switches right we used this scheme where each switch was a digit from one to a thousand and that means that the state of the switches can go from zero all the way up to 1111 right 1111 now does that seem wasteful to you I mean there's only 16 ways those switches can be positioned why would we use a variable that can go all the way up above a thousand does that seem overkill wasteful to put this in some kind of perspective look at this diagram here I show 10 cubes and each of those cubes looks like this with a thousand possible little cubes in it there's 10,000 possible little cubes each one of them represents one of the numbers in our four-digit number that means we're only using 16 out of 10,000 possible numbers that's 0.16 percent is that waste the fact that we use 10 digits is why we call our system decimal des is the latin word for 10 decimal literally means based on 10 why 10 well probably because we have 10 fingers and actually the word digit is Latin for finger in the decimal system we write digits next to each other in order to represent larger and larger numbers and as we move move to the left we have to multiply the value of the corresponding digit by 10 so this is not a 4 that is a 40 now to go to the left again we have to multiply by 10 again so this is not an 8 this is an 800 and that is not a 3 it is a 3000 why do we keep multiplying by 10 because we have 10 digits we call this base 10 we can see this in the code by making a few changes first change I made was to create this variable named base and set it equal to 10 and then over here I replaced the 1000 that used to be here when switch a was up with base times base times base or base cubed that's a thousand and I replaced the 100 with base times base or base squared that's if switch B is up and if switch C is up then I replaced the 10 with base or 10 to the first then if switch D is up I didn't change anything it's still adding a 1 because base to the 0 power is 1 this is base to the 3rd power this is base to the 2nd power this is base to the first power this is base to the 0 power now I'm going to print the current state when I run this program you will see oh yeah that's a 0 see down here right that's a 0 all the switches are down and if I set switch a sure enough that's a thousand and then if I set switch B well yes that's going to be 1100 and if I set switch see that's going to be 1110 and if I set switch D 1111 but we've only got 2 digits 0 & 1 right so doesn't that mean that we could change the base of our representation - I mean think about that for a minute as we move to the left rather than multiplying by 10 we could just multiply by 2 right well let's see let's just change our base from 10 to 2 and run the program and let's see what happens when we were in this program seems to be working properly doesn't it let's try multiple switches yes that seems to work and let's see if our delay works yep our delay seems to work everything's working fine even with a base of 2 and look down here at the the printed value of the current state if I set switch a well comes to 8 and if I set switch B well goes to 12 and switch C makes it a 14 and switch D makes it a 15 and if all the switches are down that makes it a zero our state goes from 0 to 15 that is exactly the 16 states that our switches can be in no waste all the numbers are used cool when the base is 2 we say that the system is binary which is Latin for based on 2 now the switch representation is binary and it works just fine why binary because switches only have two positions so we only need 2 digits to represent them but remember at the beginning of this episode I told you that the light switches in my basement were a kind of computer they had input they had output they had memory control and logic they are a computer but they're a computer made out of switches and as we'll learn in some upcoming episodes all computers are built out of switches special kinds of switches to be sure but still switches switches that have only two positions on and off and so computers use binary because the switches inside those computers have only two positions on or off which corresponds to just 2 digits 0 or 1 you may find this startling you may not believe it you look at your calculator for example and you see 10 digits you look at your laptop and you see numbers on the screen that have 10 digits you look at the keyboard 10 digits you look at your iPad 10 digits but I promise you deep down inside where it counts all that math all the logic all the processing is being done with numbers that have only 2 digits 0 & 1 it's all done in binary and so in upcoming episodes we're going to learn all about binary math and binary logic and boolean algebra and the whole system of concepts that allows us to describe numbers and ideas in terms of 2 digits 1 & 0 but not today today we've done enough [Music] so what have we learned well first we learned that computers are everywhere and software drives them all and then we learned that programmers are in demand and will likely stay in demand for many decades to come and finally we learned that writing code is a great way to earn a really good living next we learned that computers had input-output memory control and logic and I showed you that the light switch right outside my office door was in fact a little computer and then we discovered a second light switch and that made things a little more complicated so I showed you some boolean logic and some truth tables I showed you the tables for and and or and not and I impressed upon you the importance of learning those tables and those concepts then we found the third switch and when we wrote down the truth table for the third switch it was pretty complicated but we were able to simplify it by using a new logical operation that we called exclusive war that when we applied it twice simplified it a lot then we added the fourth switch and we found that the pattern that we had established for three switches was easily expandable to four switches that is the power of understanding the truth tables and the logic then we realized that our solution worked fine if one person operated the light switches but if two people tried to operate the light switches at the same time then it failed this is a very common problem in software and we're going to come back to it in future episodes but it's also a somewhat advanced concept so it's going to take us a little while to get back to it we also realized that what humans think of as simultaneous is probably not simultaneous to a computer because the computer is so fast we learned that when we're solving human problems we have to consider things like time from a human point of view and we learned that that was full of interesting little complications we learned that even simple systems like these light switches require disciplined thought because they're full of complicated little intricacies finally we scratched the surface of the decimal and binary number systems and I told you that computers use binary inside because computers are made of switches and switches have only two States on or off so they compute with numbers that have only 2 digits 1 or 0 ok so now I imagine you'd like to play with this computer program that we've been writing to control the light switches so here are the steps that you can follow to get it working on your computer now if you don't understand these steps you might need to get some help from someone who knows a bit about your computer system [Music] first we're using a free tool the name of that tool is processing and you can get processing at processing dot org if you go to that website this should pop up and there's lots of information on this site that will tell you how to use processing but we want to go here downloading processing right so we're gonna click on that download processing button and that brings you here to a window which allows you to make a donation if you'd like to you don't have to you can click on no donation if you want although later you might want to come back and make a donation because these guys have done a lot of very good work anyway you click on the download button and that takes you to a window which allows you to select the system that you're running I even running Mac Oz but you might be running Windows or Linux you get to choose I will download from Mac coughs you download from something else that will cause the download to begin you can see it down here it is a hundred and some megabytes so it can take a while [Music] now that the download is done you can find the downloaded file there's a number of ways to do this I've just found it by selecting a show and finder you may have a different way here it is here this is the file processing dot blah blah blah it is a zip file and so let's see if I can blow that up a little bit so you can see it processing 3.0 - Mac OS X and I've downloaded a number of times anyway I'm going to unzip it by double clicking it and you'll notice that that will unzip it for me and create yet another file called processing dot app this is the processing application and what we want to do with that is move it to the Applications folder wherever you keep your applications that's where you ought to move it and let it copy it in there and now if we go to the Applications folder or wherever you keep your applications and we look for something named processing or processing however you say it you should be able to double click it and if you double click it it should come up and open you may have to answer a few security questions here and there but ok here is processing that's what it looks like when it comes up all right now before we do anything we're gonna want to go get the source code that we were playing with in the episode so let's go to the clean coders application you're probably there already because you're watching this right so probably there look on the page for this episode and you will see a get extras so go ahead and click that and you will notice that it starts to download something and that what it's downloading is a zip file with all of the extras and you'll find that zip file somewhere the same way you found it before and it should look something like this P 101 - e 1 dash extras dot zip now what I'd like you to do is unpack that bindable clicking it or however you unpack it and that should leave you with a folder named P 101 - you won - extras and inside that folder you should find light switches dot zip which I want you to unpack again yes and that should leave you with a folder named light switches now let's go back to the processing application here's our processing application will dismiss this window because we don't really care about this window at all and up at the top you can't see it it's on my screen you can't see it that's in the menu bar there is a menu called file and what I'd like you to do is select the open item and from the open item I want you to go find that at light switches folder that you had before you just unpacked here it is let's see in P 101 extras lights which is good go into that folder and select light switches dot P de it doesn't matter which of these PDE is actually any of them but select light switches P de good and there it is there's the code okay now this is code that you haven't seen yet actually the codes the code that you've seen looks like that's just part of the light switches application you don't have to understand all of it just this part here is all you really need to understand you'll see that there's lots of extra stuff here but before we get into that there's one more step you need to follow up at the top where you can't see it on my screen is a Tools menu and if you go to that Tools menu you will see a menu item called add tool you can see that click that and click on the libraries tab scroll down until you find the sound library let's see sound there it is click it it should select it and now click the install button and it'll download the sound library and install it into processing and that's the library that makes the nice little clicking sounds that your switches will make good now you can dismiss this window here and run the program and the program should run and it should work I hope you get to this point cuz this is great isn't it I mean the programs working in everything if you got stuck along the way you might need to get some help from somebody who knows a little bit about the computer system you're using before I sign off here let me show you one other thing notice how when we run it there are four switches that show up remember also during the episode I sometimes have three switches or two switches or one switch well here are the files here that have the different number of switches so there's the four switch scenario that's the one that has all this fancy code with all the timing that we did with the Million representation of the state and so on and there's the three switch scenario which we really didn't do very much with just kind of the XOR problem remember that and there's the to switch scenario and the to switch scenario we really left well you may remember that right I'm just comparing the states of the switches directly and there's even the one switch scenario and boy oh boy that one was really simple wasn't that if the switches up the lights on otherwise it's off you can change which scenario we're running by going to the light switches tab see that up here and the light switches tab you just change that right there - OH - switch scenario and hit the Run button and now it'll come up with two switches or you can change it to three switch scenario and hit the Run button and it'll come up with the three switch scenario so you can change it to whatever you'd like for switch is where we left it right doop do and it'll work just as before so I hope you get all that working and enjoy it and remember to solve that last problem that we talked about all right hmm if someone changes the same switch several times we probably wanted to change the state of the light every time they change that switch so good luck and we'll see you on the next episode so that's it that's the episode I hope you enjoyed it I hope you learned something and I hope the episode made you want to learn more because believe me there is a lot more to learn every one of these episodes coming up we're going to learn a little bit more Java as each episode goes by your capabilities in Java will in prease but every episode is also going to focus on some aspect of computer science computer internals boolean algebra logic binary mathematics and so on we're going to learn all of the materials you need to know to be a well-rounded programmer and we're going to begin with the next episode you're not gonna wanna miss episode 2 of programming 101 logic [Applause] [Music] [Music] Benny we found a third switch and when we did the truth table for that third switch it turned out to be pretty complicated but we were able to simplify it with a new logical operation that we called exclusive war and when we used that operation twice in a row it simplified the program realized that was really dumb was really a lot it simplified the program real much no really it simplified the program a lot yeah how about that okay all right I action
Info
Channel: Clean Coders
Views: 112,312
Rating: undefined out of 5
Keywords: Clean Coders, Clean Code, Uncle Bob, iOs Development, Coding, Javascript, Computer Programming, Robert Martin, Computers, C++, SOLID Principle, TDD, Programming 101
Id: -1CuAiKdBQs
Channel Id: undefined
Length: 93min 46sec (5626 seconds)
Published: Tue Apr 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.